我正在尝试做一件非常简单的事情:当用户按下键盘上的某个键时触发一个操作
我想要映射的键是:
- 键+
- 键-
- 删除键
- ctrl+c
ctrl+v
公共(public)类 keytestmain 扩展 Applet{
//Called when this applet is loaded into the browser. public void init() { //Execute a job on the event-dispatching thread; creating this applet's GUI. try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { JLabel lbl = new JLabel("Hello World"); add(lbl); JPanel p = new JPanel(); p.setBackground(Color.green); p.setMinimumSize(new Dimension(100,100)); p.setPreferredSize(new Dimension(100,100)); p.setMaximumSize(new Dimension(100,100)); InputMap inputMap = new InputMap(); // Add a KeyStroke inputMap.put(KeyStroke.getKeyStroke("SPACE"), "actionName"); inputMap.setParent(p.getInputMap(JComponent.WHEN_FOCUSED)); p.setInputMap(JComponent.WHEN_FOCUSED, inputMap); add(p); } }); } catch (Exception e) { System.err.println("createGUI didn't complete successfully"); } }
}
但是没有效果
有什么想法吗?
最佳答案
我会使用Key Bindings ,而不是 KeyListeners。这更可靠,因为它没有太多焦点问题。此外,KeyListeners 是一个相对较旧的 AWT 解决方案,因此根据您的 JDE,该命令可能已被弃用。
关于java - Swing : detecting onKeyPressed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7100400/