0

Java 中是否有一种方法可以执行按下操作按钮?,我需要这个,因为我想制作一个 KeyListener,当您按下键盘上的按钮时,“5”会在 gui 描述“5”中启动我按钮;

编辑

我得到了 ActionListener:

public void actionPerformed(ActionEvent event){
    if(button.getLabel().equals("1")){
     // do something
    }
 }

和 KeyListener

public void keyPressed(KeyEvent e){
  if (e.getKeyCode() == VK_NUMPAD1) {
        //    do what would happen if I pressed the mouse on the button
        //    I do not know how to execute it thought that it was pressing down the 
        // button with the label '1 '
  }
}
4

2 回答 2

0

查看http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyListener.htmlhttp://docs.oracle.com/javase/7/docs/api/java/ awt/event/KeyAdapter.html,无论您喜欢匿名内部类还是接口。

例子:

panel.add(new KeyListener() {
    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == VK_NUMPAD5) {
            // do whatever you want here
            System.out.println("Numpad 5 pressed);
        }
    }
    @Override
    public void keyReleased(KeyEvent e) {}
    @Override
    public void keyTyped(KeyEvent e) {}
});

或者

panel.add(new KeyAdapter() {
    // override the method you want
    // do what you want here
});
于 2014-04-18T11:17:08.990 回答
0

下面的例子很好,你只需要在 if 语句中输入:

if (e.getKeyCode() == VK_NUMPAD5) {
    nameOfButtonToClick.doClick();
}

显然它们必须在相同的范围内,因为您的按钮可能被声明为字段值?

于 2014-04-18T11:28:03.573 回答