Search code examples
javaswingfocusjtextfieldjtextarea

Select text by default in swing


There is any way to automatically by default select text in JTextField and JTextArea when focusGained event occurs?


Solution

  • You just said how to do it -- focusGained event of a FocusListener.

    You can then get the JComponent whose focus has been gained via FocusEvent's getSource() method and then call the selectAll() method on it.

    Something like:

    FocusAdapter selectAllFocusAdapter = new FocusAdapter() {
      public void focusGained(FocusEvent e) {
        final JTextComponent tComponent = (JTextComponent) e.getSource();
        SwingUtilities.invokeLater(new Runnable() {
    
          @Override
          public void run() {
            tComponent.selectAll();
          }
        });
        tComponent.selectAll();
      }
    };
    
    myJTextField.addFocusListener(selectAllFocusAdapter);
    otherJTextField.addFocusListener(selectAllFocusAdapter);
    myTextArea.addFocusListener(selectAllFocusAdapter);