【问题标题】:KeyListener java, executes button's actionKeyListener java,执行按钮的动作
【发布时间】:2014-04-18 11:11:28
【问题描述】:

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 '
  }
}

【问题讨论】:

  • 不清楚你在问什么。你试过什么?
  • 是的,它被称为 KeyListener。问题可能是您将此侦听器绑定到的组件(当它处于活动状态时)或您用于键盘的键码。显示一些代码。

标签: java button keylistener keypad


【解决方案1】:

查看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
});

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2015-01-12
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多