按住键后执行某项操作,并在释放并按下该键时重复进行 [英] do something once the key is held and repeat when its released and repressed
问题描述
我需要检查用户何时按下某个键并将其释放. 如果按住某个键,我将执行一次操作.
I need to check when the user presses on a key and releases it. If a key is held in, I will do something once.
我使用按键来获取要与之关联的按钮. 我还使用了一个信号量来克服这个问题,但是看起来很疯狂
I used the keystroke to get the button I want to relate an action with. I used also a semaphore to overcome this problem but it looks crazy
我的代码: `
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"键时,它会打印: 错误的 真的 错误的 真的 错误的 是
When I press "1" key and hold it, it prints: false true false true false true
谢谢.
推荐答案
我不相信您可以在Linux中实现所需的功能,因为操作系统会不断向JVM发出按下/释放信号.
I don't believe you can achieve what you need in Linux, because the operating system continually issues press/release signals to the JVM.
请参见
- How to stop repeated keyPressed() / keyReleased() events in Swing
- How to know when a user has really released a key in Java?
这篇关于按住键后执行某项操作,并在释放并按下该键时重复进行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!