2

I have a JButton and a JTextField on a JFrameFrom. I want to enter some data in text field and then when I press enter key, an event occurs without set focus on the button. some thing like Yahoo log-in page. You can enter username and password and without traversing the focus to the sign-in button, when press enter, sign-in will occur. How could I do this?

Roman C
  • 49,761
  • 33
  • 66
  • 176
zari
  • 1,709
  • 1
  • 12
  • 18
  • 1
    Give the textbox KeyListeners that wait for Enter to be pressed, then execute the button's method. – Kon Jul 06 '13 at 20:18
  • 1
    @Kon No need for that. Even if there is a need, using `KeyListener` would be dissadvantage. – Branislav Lazic Jul 06 '13 at 20:28
  • 1
    ActionListener, nothing more. Already answered http://stackoverflow.com/questions/4419667/detect-enter-press-in-jtextfield – udalmik Jul 06 '13 at 20:30

1 Answers1

2

If I understood your question good, solution should be easy. Just add ActionListener on JTextField:

textField.addActionListener(new ActionListener(){
    
    public void actionPerformed(ActionEvent e){
        //Do stuff...
    }

});

When JTextField is focused and when you hit an Enter key, event will occur.

Abra
  • 19,142
  • 7
  • 29
  • 41
Branislav Lazic
  • 14,388
  • 8
  • 60
  • 85