javaswingselectionjtextarea

Which event fires when text is selected in a JTextArea?


I want to monitor the selection of text in a JTextArea, but I don't know what type of event to listener for.

How do I listen for text selections?


Solution

  • I don't know about any "selection listeners" for text components (although they might be useful), but you could use a CaretListener to monitor changes to the caret position and check the selection state...

    public class TestSelectionMonitor {
    
        public static void main(String[] args) {
            new TestSelectionMonitor();
        }
    
        public TestSelectionMonitor() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    final JTextArea ta = new JTextArea();
                    ta.addCaretListener(new CaretListener() {
                        @Override
                        public void caretUpdate(CaretEvent e) {
                            int length = ta.getSelectionEnd() - ta.getSelectionStart();
                            System.out.println(length);
                        }
                    });
    
                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new JScrollPane(ta));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    }