Search code examples
javaswingfocusjtextfield

switching JTextFields by pressing Enter key


I have created number of text fields and I'm wonder how can I switch the focus between the fields by pressing the enter key.

In addition, Can I control the Target field ? for example can I defined that by pressing Enter in field A the focus will be change to field C ?

enter image description here


Solution

  • Simple example:

    Suppose you have two JTextFields: textField and textField1

    textField.addActionListener(new ActionListener() {
       @Override
        public void actionPerformed(ActionEvent e) {
          textField1.requestFocusInWindow();    
        }
    }); 
    
    textField1.addActionListener(new ActionListener() {
       @Override
       public void actionPerformed(ActionEvent e) {
          textField.requestFocusInWindow(); 
       }
    }); 
    

    Now when you hit Enter when focused on the first JTextField, the other one will be focused, and vice versa.