How do you make key bindings for a java.awt.Frame?(如何为 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 进行键绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何为 java.awt.Frame 进行键绑定?
基础教程推荐
- 在螺旋中写一个字符串 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01