Java Swing How to - Select all text for double clicking








Question

We would like to know how to select all text for double clicking.

Answer

import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
//  www .j av  a  2 s  .co m
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;

public class Main {

  public static void main(String[] args) {
    final JTextPane tp = new JTextPane();
    JButton withFocus = new JButton("Select with focus");
    tp.addMouseListener(new MouseAdapter() {

      @Override
      public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) {
          tp.selectAll();
        }
      }

    });

    JFrame frame = new JFrame("Testing");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    frame.add(new JScrollPane(tp));
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}