Java Swing How to - Get selection from JTextPane








Question

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

Answer

import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.Highlighter.Highlight;
/*  w  ww .j a  va 2s  . c  om*/
public class Main extends JFrame {
  public Main() {
    setSize(300, 200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    final JTextPane textPane = new JTextPane();
    add(textPane);
    textPane.addCaretListener(new CaretListener() {
      public void caretUpdate(CaretEvent e) {
        Highlight[] h = textPane.getHighlighter().getHighlights();
        for (int i = 0; i < h.length; i++) {
          System.out.println(h[i].getStartOffset());
          System.out.println(h[i].getEndOffset());
        }

      }
    });
  }

  public static void main(String args[]) {
    new Main().setVisible(true);
  }
}