2014-12-13 69 views
0

我正在用簡單的GUI構建簡單的聊天應用程序,但是我有一個問題,將Enter鍵指定給發送按鈕。現在按Alt + Enter是非常不切實際的。添加Enter鍵作爲JButton加速器

public void buildInterface() { 
    //some other components 
    btnSend = new JButton("Send"); 
    btnExit = new JButton("Exit"); 
    btnSearch=new JButton("Search"); 
    btnSend.setMnemonic(KeyEvent.VK_ENTER); 

    JPanel box=new JPanel(); 
    add(box, BorderLayout.SOUTH); 
    box.add(tfInput); 
    box.add(btnSend); 
    box.add(btnExit); 
    box.add(btnSearch); 
} 

回答

1

當按鈕被聚焦,在大多數的外觀和感覺輸入將激活按鈕。

但是,您可以指定一個按鈕作爲該窗口的「默認」按鈕,只要被聚焦的組件不消耗該按鈕,該按鈕將在按下按鈕時激活。

How to Use Root PanesJRootPane#setDefaultButton更多細節

1

添加以下代碼到你的Util類

public static void bindKeyStroke(final JButton btn, String ks) { 
    final ActionListener[] alist = btn.getActionListeners(); 
    if (alist.length != 0) { 
     AbstractAction action = new AbstractAction(btn.getText(), btn.getIcon()) { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       for (ActionListener al : alist) { 
        ActionEvent ae = new ActionEvent(e.getSource(), e.getID(), Action.ACCELERATOR_KEY); 
        al.actionPerformed(ae); 
       } 
      } 
     }; 

     KeyStroke keyStroke = KeyStroke.getKeyStroke(ks); 
     btn.setAction(action); 
     btn.getActionMap().put(Action.ACCELERATOR_KEY, action); 
     btn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, Action.ACCELERATOR_KEY); 
    } 
} 

轉到框,對話框或面板的構造和initComponent之後添加();

Util.bindKeyStroke(<your button>, "alt enter"); 

修復雙動作,在動作進行

if (evt.getActionCommand().equals(Action.ACCELERATOR_KEY)) { 
    // Your send action here 
}