2011-01-26 41 views

回答

13

你應該爲JButton使用Action

Action sendAction = new AbstractAction("Send") { 
    public void actionPerformed(ActionEvent e) { 
     // do something 
    } 
}; 

JButton button = new JButton(sendAction); 

然後你可以爲JTextField甚至在一個設置相同的動作MenuItem如果你想同樣的動作在菜單可供選擇:

JTextField textField = new JTextField(); 
textField.setAction(sendAction); 
7

像這樣的東西應該工作:

textField.addActionListener(new ActionListener() 
{ 
    @Override 
    public void actionPerformed(ActionEvent e) 
    { 
     button.requestFocusInWindow(); 
    } 
}); 
+0

我只是去嘗試做到這一點,它把專注於按鈕,但它不會激活它。 – LOD121 2011-01-26 22:49:43

+0

它不會,requestFocusInWindow()方法會執行它所說的任務。要模擬點擊,doClick()方法就是你要做的。 – berry120 2011-01-26 22:52:21

+2

button.doClick();效果很好。謝謝。 – LOD121 2011-01-26 22:55:04

3

我會做類似如下:

textField.addKeyListener(
    new KeyAdapter() { 
    public void keyPressed(KeyEvent e) { 
     if (e.getKeyCode() == KeyEvent.VK_ENTER) { 
      button.doClick(); 
     } 
    } 
    }); 
} 
4

您可以通過添加default行爲的按鈕,這樣

cmdLogin.setDefaultCapable(true); // by default, this is true 
this.getRootPane().setDefaultButton(cmdLogin); // here `this` is your parent container 
相關問題