Search code examples
javajtextfield

Selecting all text when clicking or pressing TAB on JTextField


How can I set up the JTextField so that, when the user clicks on it or presses the TAB key, the text of JTextField is selected?


Solution

  • Add a FocusListener to the JTextField, and in focusGained(), call selectAll().

    In code, this looks like this:

    yourTextField.addFocusListener(new FocusListener() {
        @Override
        public void focusGained(FocusEvent e) {
           ((JTextField)e.getSource()).selectAll();
        }
    
        @Override
           public void focusLost(FocusEvent e) {}
    });