开发者

Enter key focus for a JButton in java swing?

开发者 https://www.devze.com 2023-01-14 02:21 出处:网络
How to make Enter key focus for a JButton in java swing? i have done like this btn_Login.registerKeyboardAction(new ActionListener() {

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("ent开发者_JS百科er key pressed");

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

but not working


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.


Thanks to all! Here are some notes that I found out to fix the enter problem for the Nimbus Look and fell.

  1. The enter key works with linux but not with windows ( Nimbus ).
  2. For windows the actual "doClick" of the button is done with space ( Key Char 32 ).
  3. It's possible to set the "enter" to do a click, but it must be done AFTER setting your Nimbus Look and Feel.
  4. Here is the code that is used in my application.

        UIManager.setLookAndFeel(new NimbusLookAndFeel());
        //- hack pour que les bouttons qui ont le focus fassent un doClick
        //- lorsque "enter" est taper.  Auparavant, c'etait l'espace qui 
        //- activait le doClick.
        InputMap im = (InputMap)UIManager.get("Button.focusInputMap");
        im.put( KeyStroke.getKeyStroke( "ENTER" ), "pressed" );
        im.put( KeyStroke.getKeyStroke( "released ENTER" ), "released" );
    

( Sorry for my french comments ! ).

0

精彩评论

暂无评论...
验证码 换一张
取 消