I'm using two JTextField
in Java Swing form. Now I enter the values in JTextField1
. Next if I press ENTER KEY means the cursor move to JTextField2
. How to do this?
Asked
Active
Viewed 4,716 times
4

Chandrayya G K
- 8,719
- 5
- 40
- 68

java872
- 89
- 1
- 3
- 5
2 Answers
11
Add an ActionListener
to the first text field. In the ActionEvent
you can get the source object, cast it to a JTextField
and then invoke the transferFocus()
method.

Andrew Thompson
- 168,117
- 40
- 217
- 433

camickr
- 321,443
- 19
- 166
- 288
1
Use actionListener
for the textField
.
Code snippet:
textField1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
textField1.transferFocus();
}
});

Mohammad Faisal
- 5,783
- 15
- 70
- 117
-
1-1, if you read the API the use of the requestFocus() method is discouraged in favour of the of the requestFocusInWindow() method. – camickr Dec 21 '11 at 06:25
-
@camickr: why you had done -1 beside that my code is working. The user is free to accept either the answer. – Mohammad Faisal Dec 21 '11 at 06:36
-
@MohammadFaisal: "The code is running", this is not valid in all situations. Sometimes performance comes to the picture. – Harry Joy Dec 21 '11 at 06:45
-
I gave the reason. The API suggests using a different method. Just because code works, does not mean it should be used. – camickr Dec 21 '11 at 06:47
-
3I would still down vote the answer. First, the suggestion to use an ActionListener was given 20 minutes before your answer so there is no need for a duplicate answer. Secondly, referencing a class variable in the ActionListener is unnecessary. As I mentioneded in my answer you have access to the source object in the ActionEvent. – camickr Dec 21 '11 at 07:00
-
@camickr: I'm not actually getting what you wanna say! Please make me correct by explaining your line `As I mentioneded in my answer you have access to the source object in the ActionEvent`. I think you must edit your answer with an example. – Mohammad Faisal Dec 21 '11 at 07:10
-
2Check out the API ActionEvent.getSource(). This method will return the Swing component that generated the ActionEvent, so you can reference this when transfering focus instead of using a class variable to keep track of the text field. This also allows you to reuse the class since you wrote generic code, not code specific to on text field. – camickr Dec 21 '11 at 16:09