如何为 java.awt.Frame 进行键绑定? [英] How do you make key bindings for a java.awt.Frame?

查看:31
本文介绍了如何为 java.awt.Frame 进行键绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的窗口是一个 java.awt.Frame,Frame 内部是两个面板 (java.awt.Panel).我正在尝试让窗口处理我按下的按钮.

My window is a java.awt.Frame, and inside of the Frame are two Panels (java.awt.Panel). I'm trying to make it so that the window handles buttons I press.

我尝试使用 KeyListener,使 Frame 实现 KeyListener.我将 KeyListener 添加到 Frame 中,但是当我按下键时 KeyListener 函数没有做任何事情.(我尝试使用 System.out.println() 进行打印.)

I tried using a KeyListener, making the Frame implement the KeyListener. I added the KeyListener to the Frame, but the KeyListener functions didn't do anything when I pressed keys. (I tried printing with System.out.println().)

我尝试按照本教程进行操作:http://tips4java.wordpress.com/2008/10/10/键绑定/ .这是我尝试处理按空格键的操作:

I tried following this tutorial: http://tips4java.wordpress.com/2008/10/10/key-bindings/ . Here is the my attempt to handle pressing the SPACEBAR:

public void registerActions(){                                  //01
  Action myAction = new AbstractAction(){                       //02
    @Override                                                   //03
    public void actionPerformed(ActionEvent e) {                //04
      System.out.println("GREAT SUCCESS!");                     //05
    }                                                           //06
  };                                                            //07
  KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0); //08
  component.getInputMap().put(key, "myAction");                 //09
  component.getActionMap().put("myAction", myAction);           //10
}                                                               //11

主要问题是我不知道第 09 行中的组件"应该是什么10,因为我的应用程序没有任何 JComponents.

The main problem is that I don't know what 'component' should be in lines 09 & 10, because my application does not have any JComponents.

有没有办法在不使用摆动组件的情况下做到这一点?还是有其他处理按键的方法?

Is there a way to do this without using swing components? Or is there another way to handle key presses?

推荐答案

我发现我可以使用 AWTEventListener 来做到这一点.

I found that I could do this with an AWTEventListener.

public class MyFrame extends Frame implements AWTEventListener {

  ...

  public MyFrame(String title){
    super(title);
    ...
    this.getToolkit().addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK);
  }

  @Override
  public void eventDispatched(AWTEvent event) {
    if(event instanceof KeyEvent){
      KeyEvent key = (KeyEvent)event;
      if(key.getID()==KeyEvent.KEY_PRESSED){ //Handle key presses
        System.out.println(key.getKeyChar());
        //TODO: do something with the key press
        key.consume();
      }
    }
  }
}

这篇关于如何为 java.awt.Frame 进行键绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆