Java 动作监听器,键盘输入
我对行动听众有问题。 问题是:Java 动作监听器,键盘输入,java,swing,action,actionlistener,Java,Swing,Action,Actionlistener,我对行动听众有问题。 问题是: private static void createAndShowGUI() { int i; System.out.println("Created GUI on EDT? "+ SwingUtilities.isEventDispatchThread()); JFrame f = new JFrame("Best Game Ever"); JButton buttonA = new JButton("P
private static void createAndShowGUI() {
int i;
System.out.println("Created GUI on EDT? "+
SwingUtilities.isEventDispatchThread());
JFrame f = new JFrame("Best Game Ever");
JButton buttonA = new JButton("Press 'z'");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MyPanel(),BorderLayout.CENTER);
f.add(buttonA, BorderLayout.PAGE_END);
f.pack();
f.setVisible(true);
final char ACTION_KEY = 'z';
final char ACTION_KEY2 ='x';
Action actionListener = new AbstractAction()
{
public void actionPerformed(ActionEvent actionEvent)
{
}
};
Action actionListener2 = new AbstractAction()
{
public void actionPerformed(ActionEvent actionEvent)
{
System.out.println("x");
}
};
KeyStroke z = KeyStroke.getKeyStroke('z');
InputMap inputMap = buttonA.getInputMap();
inputMap.put(z, ACTION_KEY);
ActionMap actionMap = buttonA.getActionMap() ;
actionMap.put(ACTION_KEY, actionListener);
KeyStroke x = KeyStroke.getKeyStroke('x');
InputMap inputMap2 = buttonA.getInputMap();
inputMap2.put(x, ACTION_KEY2);
ActionMap actionMap2 = buttonA.getActionMap();
actionMap2.put(ACTION_KEY2, actionListener2);
}
我只是不能为它编一个只打印x一次的代码,即使我拿着钥匙。
谢谢
很抱歉,没有放入所有代码:(
希望现在有意义
“我就是不能为它编一个代码,即使我拿着钥匙,它也只能打印x一次。”
一种方法是将released
添加到kestroke中,它只会在按键释放时打印
inputMap.put(KeyStroke.getKeyStroke("released X"), "printX");
击键表示键盘或等效输入设备上的键操作。击键只能对应于按下或释放特定键,就像按下键和释放键一样;或者,它们可以对应于键入特定Java字符,就像键入键一样
您也可以尝试
键入
,但“键键入”事件在每个平台上运行。它在Windows上不起作用,我只是尝试了它您的操作在哪里触发???您面临的问题是什么?
Here's an example
import java.awt.event.ActionEvent;
import javax.swing.*;
public class TestKeyBind {
public TestKeyBind() {
JPanel panel = new JPanel();
Action actionListener2 = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("x");
}
};
InputMap inputMap = panel.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = panel.getActionMap();
inputMap.put(KeyStroke.getKeyStroke("released X"), "printX");
actionMap.put("printX", actionListener2);
JFrame frame = new JFrame();
frame.add(panel);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TestKeyBind();
}
});
}
}