Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to associate pressing "enter" with clicking button?

In my swing program I have a JTextField and a JButton. I would like for, once the user presses the "enter" key, the actionListener of the JButton runs. How would I do this? Thanks in advance.

like image 575
Connor Avatar asked Jan 16 '11 00:01

Connor


People also ask

How do you make button click on enter?

To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.

How do you trigger a click event on pressing Enter key react?

Using the onKeypress event The onKeyPress event is fired when a user presses the key on a keyboard, so that by using this we can trigger the button click by pressing a Enter key. The keyCode for the Enter key is 13.

How do you trigger button click on enter in angular?

We can use angular keydown event to use Enter key as our submit key. Add keydown directive inside the form tag. Create a function to submit the form as soon as Enter is pressed. Assign the keydown event to the function.


2 Answers

JRootPane has a method setDefaultButton(JButton button) that will do what you want. If your app is a JFrame, it implements the RootPaneContainer interface, and you can get the root pane by calling getRootPane() on the JFrame, and then call setDefaultButton on the root pane that was returned. The same technique works for JApplet, JDialog or any other class that implements RootPaneContainer.

like image 73
Hovercraft Full Of Eels Avatar answered Nov 12 '22 22:11

Hovercraft Full Of Eels


there is an example here

http://www.java2s.com/Code/Java/Swing-JFC/SwingDefaultButton.htm

this is what you need: rootPane.setDefaultButton(button2);

like image 24
alampada Avatar answered Nov 12 '22 21:11

alampada