Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 334
Gil Peretz Avatar asked Feb 27 '26 21:02

Gil Peretz


1 Answers

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.

like image 130
Maroun Avatar answered Mar 01 '26 11:03

Maroun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!