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.
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.
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.
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.
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);
Something like this should work:
textField.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
button.requestFocusInWindow();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With