Search code examples
javaswingfocusjbutton

Set default focus on JButton


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?


Solution

  • 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.