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.
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.
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.
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.
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.
there is an example here
http://www.java2s.com/Code/Java/Swing-JFC/SwingDefaultButton.htm
this is what you need: rootPane.setDefaultButton(button2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With