2014-11-25 106 views
0

,我收到了麻煩,當我寫這篇文章的代碼一個JButton打開新jfame和一切是通過使用「回車鍵」,但它沒有工作,這個代碼我已經writen:什麼是ActionListener以及如何使用它來處理Enter鍵?

if(evt.getKeyCode()==KeyEvent.VK_ENTER){ 
    Chooser ch = new Chooser(); 
     ch.setVisible(true); 
} 

但我得到了答案,其中包含輸入密鑰不能與事件一起工作,它只是與Action Listner的原因?

回答

0

您應該使用KeyBinding,然後在組件中註冊操作,或者在此情況下按鈕。這是一個小小的代碼片段。

 JButton btn = new JButton("Open Window"); //creates the button 
    //registers the KeyStroke with the button 
    btn.getInputMap().put(KeyStroke.getKeyStroke("released ENTER"), "released"); 
    //creates an action for the component 
    Action exit = new AbstractAction() { 
     public void actionPerformed(ActionEvent e) { 
      JOptionPane.showMessageDialog(btn, "You pressed the enter key"); 
     } 
    }; 
    //registers the Action with the corresponding keystroke on the button component 
    //@param exit is the action to be performed 
    btn.getActionMap().put("released",exit); 

我建議你閱讀有關使用鍵綁定Here

相關問題