Java Swing How to - Highlight all the text in JTextPane








Question

We would like to know how to highlight all the text in JTextPane.

Answer

import java.awt.BorderLayout;
//w  ww .j  a v a 2  s.c om
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;

public class Main {

  public static void main(String[] args) {
    final JTextPane tp = new JTextPane();
    JButton withFocus = new JButton("Select with focus");
    withFocus.addActionListener(e -> {
      tp.selectAll();
      tp.requestFocus();
    });
    JButton withOutFocus = new JButton("Select without focus");
    withFocus.addActionListener(e -> tp.selectAll());

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    frame.add(new JScrollPane(tp));
    JPanel panel = new JPanel();
    panel.add(withFocus);
    panel.add(withOutFocus);
    frame.add(panel, BorderLayout.SOUTH);
    frame.pack();
    frame.setVisible(true);
  }
}