0
votes

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?

1
why do you want to invoke enter an any of the textfields? - Khinsu
@TimHerold May be the submit form functionality :) - Suresh Atta
Submit.doClick(); if is about Swing - mKorbel
@mKorbel . but how does a program click be a listener for enter key? - user2670866
add ActionListener to every JTextFields, never to use KeyListener for JTextComponents - mKorbel

1 Answers

2
votes

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 :)