我需要检查当用户按下一个键并释放。 如果某个键时,我会做一些一次。
我用按键来获得我想要关联与动作的按钮。 我还用旗语来克服这个问题,但它看起来疯狂
我的代码:`
InputMap inputMap = jPanel1.getInputMap();
KeyStroke keyPressed = KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, false);
KeyStroke keyReleased = KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, true);
//------------------------------------------
jPanel1.getActionMap().put("_1000Press", _1000Press);
inputMap.put(keyPressed, "_1000Press");
jPanel1.getActionMap().put("_1000Release", _1000Release);
inputMap.put(keyReleased, "_1000Release");
public Action _1000Press = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if(!one){
// do some thing
one = true;
System.out.println(one);
}
}
};
public Action _1000Release = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
one = false;
System.out.println(one);
}
};
`
当我按“1”键不放,它打印:假的真假真假真
提前致谢。
这对我来说工作正常
InputMap im = getInputMap();
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, false), "Press");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, true), "Release");
am.put("Press", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (!pressed) {
pressed = true;
System.out.println("press");
}
}
});
am.put("Release", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (pressed) {
pressed = false;
System.out.println("release");
}
}
});
只是,以确保我这样做
am.put("Release", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
pressed = false;
System.out.println("release");
}
});
它仍然工作
印刷press
时,我按住1,然后打印release
,当我解开密钥。 这是我唯一的输出
有完整的代码已更新
public class TestPane extends JPanel {
private boolean pressed;
public TestPane() {
InputMap im = getInputMap();
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, false), "Press");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, true), "Release");
am.put("Press", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (!pressed) {
pressed = true;
System.out.println("press");
}
}
});
am.put("Release", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (pressed) {
pressed = false;
System.out.println("release");
}
}
});
}
}
我不相信你可以在Linux中需要什么,因为操作系统不断发出按下/释放信号到JVM。
看到
- 如何制止重复的keyPressed()/的keyReleased()在Swing事件
- 如何知道用户何时真正发布Java中的一个关键?
文章来源: do something once the key is held and repeat when its released and repressed