Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enter key focus for a JButton in java swing?

Tags:

java

key

swing

How to make Enter key focus for a JButton in java swing?

i have done like this

btn_Login.registerKeyboardAction(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
       System.out.println("enter key pressed");

    }
}, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0,false), txt_Username.WHEN_FOCUSED);

but not working

like image 282
Lalchand Avatar asked Apr 10 '26 12:04

Lalchand


1 Answers

I assume you want a specific button to be "pressed" if you just press Enter on a certain window.

To do this, you have to set the defaultButton on your RootPane of the current JFrame.

Here is an example:

 JButton btn = new JButton();
 JFrame frame = new JFrame();

 frame.getContentPane().add(btn);
 frame.getRootPane().setDefaultButton(btn);

That should give you the expected result.

like image 143
Jens K. Avatar answered Apr 12 '26 02:04

Jens K.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!