Detect enter press in JTextField
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.
A JTextField
was designed to use an ActionListener
just like a JButton
is. See the addActionListener()
method of JTextField
.
For example:
Action action = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("some action");
}
};
JTextField textField = new JTextField(10);
textField.addActionListener( action );
Now the event is fired when the Enter key is used.
Also, an added benefit is that you can share the listener with a button even if you don't want to make the button a default button.
JButton button = new JButton("Do Something");
button.addActionListener( action );
Note, this example uses an Action
, which implements ActionListener
because Action
is a newer API with addition features. For example you could disable the Action
which would disable the event for both the text field and the button.
JTextField function=new JTextField(8);
function.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//statements!!!
}});
all you need to do is addActionListener to the JTextField like above! After you press Enter the action will performed what you want at the statement!
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.
}
}