如何为java.awt.Frame进行键绑定? [英] How do you make key bindings for a 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/key-bindings/.这是我尝试按下空格键的尝试:
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行和第9行中的组件"应该是什么. 10,因为我的应用程序没有任何JComponent.
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屋!