Is it possible to detect when someone presses Enter while typing in a JTextField in java? Without having to create a button and set it as the default.
First add action command on JButton or JTextField by:
JButton.setActionCommand("name of command");
JTextField.setActionCommand("name of command");
Then add ActionListener to both JTextField and JButton.
JButton.addActionListener(listener);
JTextField.addActionListener(listener);
After that, On you ActionListener implementation write
@Override
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Your actionCommand for JButton") || actionCommand.equals("Your actionCommand for press Enter"))
{
//Do something
}
}
Just use this code:
SwingUtilities.getRootPane(myButton).setDefaultButton(myButton);
Add an event for KeyPressed
.
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
// Enter was pressed. Your code goes here.
}
}
public void keyReleased(KeyEvent e)
{
int key=e.getKeyCode();
if(e.getSource()==textField)
{
if(key==KeyEvent.VK_ENTER)
{
Toolkit.getDefaultToolkit().beep();
textField_1.requestFocusInWindow();
}
}
To write logic for 'Enter press' in JTextField
, it is better to keep logic inside the keyReleased()
block instead of keyTyped()
& keyPressed()
.