Java set focus on JButton when pressing enter
Something like this should work:
textField.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
button.requestFocusInWindow();
}
});
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);