Java Swing How to - Get text from JTextPane








Question

We would like to know how to get text from JTextPane.

Answer

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//from  w  w w .  j  a v a  2 s. c  o m
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.WindowConstants;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();

    JTextPane codearea = new JTextPane();
    JScrollPane scroll;
    scroll = new JScrollPane(codearea,
        ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scroll.setPreferredSize(new Dimension(300, 300));

    JPanel panel = new JPanel(new BorderLayout());
    panel.add(scroll, BorderLayout.CENTER);
    JButton comp = new JButton("Print text");
    comp.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        System.out.println(codearea.getText());
      }
    });
    panel.add(comp, BorderLayout.SOUTH);

    frame.getContentPane().add(panel);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);

  }
}