Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java set focus on JButton when pressing enter

Tags:

java

swing

How can I make it so that when I press enter in a JTextField it activates a specific JButton? What I mean is something along the lines of a web page form where you can press enter to activate the button in the form.

like image 289
LOD121 Avatar asked Jan 26 '11 22:01

LOD121


People also ask

How do you call a method when a JButton is pressed?

If you know how to display messages when pressing a button, then you already know how to call a method as opening a new window is a call to a method. With more details, you can implement an ActionListener and then use the addActionListener method on your JButton.

Which method do you use to set text for JButton?

By default, we can create a JButton with a text and also can change the text of a JButton by input some text in the text field and click on the button, it will call the actionPerformed() method of ActionListener interface and set an updated text in a button by calling setText(textField.

How do I get focus in Java?

To obtain the focus, you have to ask focus after the add of the component but before the display of the window. Before Java 1.4, you needed to use the requestFocus() method, but now it is not a good idea to use it, because it give also focus to the window of the component, and that's not always possible.


2 Answers

You should use an Action for the JButton:

Action sendAction = new AbstractAction("Send") {
    public void actionPerformed(ActionEvent e) {
         // do something
    }
};

JButton  button = new JButton(sendAction);

Then you can set the same action for a JTextField or even on a MenuItem if you want the same action to be available in the Menu:

JTextField textField = new JTextField();
textField.setAction(sendAction);
like image 94
Jonas Avatar answered Oct 02 '22 16:10

Jonas


Something like this should work:

textField.addActionListener(new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        button.requestFocusInWindow();
    }
});
like image 25
Uhlen Avatar answered Oct 02 '22 17:10

Uhlen