Reputation: 98
Please do note that this is a different question,
I am writing a java program. I have a form with 10 JTextFields and a 'Submit' button. How do I make the method for 'Submit' button to be called when the user presses the enter key on ANY of the 10 text fields?
Should I add KeyListeners to all of the 10 or is there a more efficient way since the text fields and the button are inside a JPanel?
Upvotes: 0
Views: 1099
Reputation: 122026
No, Create an common event handler like this ,And attach it to all
Below is a Mock code:
KeyAdapter event= new KeyAdapter() {
public void keyReleased(KeyEvent e) {
//do something
}
public void keyTyped(KeyEvent e) {
// TODO: Do something for the keyTyped event
}
public void keyPressed(KeyEvent e) {
// TODO: Do something for the keyPressed event
}
});
txtField1.addKeyListener(event);
txtField2.addKeyListener(event);
-----
may be a loop also :)
Upvotes: 2