将按钮单击事件传递给actionPerformed按下按键

时间:2012-01-26 01:48:03

标签: java awt actionlistener keylistener keyevent

我正在进行必须使用AWT完成的Java分配。我想在按钮处于焦点时按下回车键来触发按钮。我想知道如何使用doClick()方法在Swing中执行此操作,但这似乎在AWT中不起作用。到目前为止,我正在尝试这个:

button.addActionListener(this); // Passes value from a TextBox to actionPerformed() 

button.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent e) {
         if(e.getKeyCode()==KeyEvent.VK_ENTER) {
              actionPerformed(null);
         }
    } 
});

public void actionPerformed (ActionEvent e) {
     try {  
          if (e.getSource() == button) {
               // Stuff I want to happen
          } else if (e.getSource() == anotherButton) {
               // Other Stuff
          } else {     //third button
               // More stuff
          }
     } catch (NumberFormatException nfe) { 
          // Null argument in keyPressed triggers this
          // catches empty string exception from TextBox
     }
 }

正如我在评论中提到的,null参数将触发catch。有没有人知道按钮按下可能是什么参数或者可能是一个更简单的方法来解决这个问题?感谢。

编辑 - 澄清:actionPerformed()使用TextBox的输入执行三项操作之一,具体取决于单击三个按钮中的哪一个。 try / catch用于捕获空字符串/格式异常。

1 个答案:

答案 0 :(得分:5)

您总是可以使用onButtonPress()之类的方法,actionPerformed可以调用的方法,以及keyPressed

  button.addActionListener(this);

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

public void actionPerformed (ActionEvent e) {
    if (e.getSource() == button){
       onButtonPress();
    } 
 }

private void onButtonPress(){
    // do something
}
相关问题