2010-09-03 29 views
2

如何在java swing中輸入JButton的關鍵焦點?在java swing中輸入JButton的關鍵焦點?

我已經做過這樣的

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); 

但不工作

+0

請參閱此鏈接http://www.devx.com/DevX/Tip/31605 – Hukam 2010-09-03 09:58:17

回答

6

我假設你想要一個特定的按鈕,「壓」,如果你只是按Enter鍵在某一窗口。

爲此,您必須在當前JFrame的RootPane上設置defaultButton。

下面是一個例子:

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

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

這應該給您預期的結果。

3

謝謝大家!這裏有一些筆記,我發現這些筆記可以解決Nimbus Look的輸入問題並且會崩潰。

  1. 回車鍵適用於linux,但不適用於Windows(Nimbus)。
  2. 對於windows,按鈕的實際「doClick」是用空格(Key Char 32)完成的。
  3. 可以設置「輸入」進行點擊,但必須在設置好Nimbus外觀後進行。
  4. 這是在我的應用程序中使用的代碼。

    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"); 
    

(對不起,我的法語評論!)。