Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 552
a sandwhich Avatar asked Dec 11 '10 23:12

a sandwhich


People also ask

What happens if you press Enter in JTextField?

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.

How can I tell if JTextField is empty?

Since we created an instance of the TextField class named text, we take text and get its value and use the isEmpty() function to see whether it is empty or not. And this is all that is required to check whether a text field is empty or not in a JavaFX application.

Can the program put text in JTextField?

The class JTextField is a component that allows editing of a single line of text.


1 Answers

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.

like image 166
camickr Avatar answered Oct 21 '22 04:10

camickr