Java Swing How to - Get selected text








Question

We would like to know how to get selected text.

Answer

//from   ww  w. ja va  2s.  co m
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextPane;

public class Main {
  public static void main(String[] args) {
    JTextPane jTextPane = new JTextPane();
    JFrame frame = new JFrame("Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.pack();
    frame.setVisible(true);

    JButton btnGetSelectedText = new JButton("Get selected text");
    btnGetSelectedText.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        System.out.println(jTextPane.getSelectedText());
      }
    });
    frame.getContentPane().add(jTextPane, BorderLayout.NORTH);
    frame.getContentPane().add(btnGetSelectedText, BorderLayout.SOUTH);
  }
}