Java Swing How to - Output Document model from JTextArea








Question

We would like to know how to output Document model from JTextArea.

Answer

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.text.AbstractDocument;
/*from   w  w  w.  j  a v a  2s .  c  o m*/
public class Main {
    public static void main(String[] args) {
        JFrame f = new JFrame();
        JTextArea ta = new JTextArea(5, 32);
        ta.setText("That's one small step for man...\nOne giant leap for mankind.");
        ta.setLineWrap(true);
        ta.setWrapStyleWord(true);

        f.getContentPane().add(ta);
        f.setSize(100, 100);
        f.setVisible(true);

        ((AbstractDocument) ta.getDocument()).dump(System.out);
    }
}

The code above generates the following result.