Swing的KeyListener和多个键同时按下 [英] Swing's KeyListener and multiple keys pressed at the same time
本文介绍了Swing的KeyListener和多个键同时按下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当同时按下两个键盘按键时,是否存在跟踪事件的常规方法?
我有几个想法,例如记住密钥和事件生成时间,以便我们可以在连续的事件处理程序调用中检查这两个事件之间的时间差并决定它是否是一个双按钮事件。但它看起来像一个kludge。
is there any conventional way in swing of tracking down the events, when two keyboard keys are pressed at the same time? I have a couple of ideas e.g. remembering the key and event generation time so that we could in a consecutive event handler invocation check the time difference between these two events and decide, whether it's a two-button event or not. But it looks like a kludge.
推荐答案
使用集合记住当前按下了哪些键并检查是否有多个键每按一次键就按下一次键。
Use a collection to remember which keys are currently pressed and check to see if more than one key is pressed every time a key is pressed.
class MultiKeyPressListener implements KeyListener {
// Set of currently pressed keys
private final Set<Character> pressed = new HashSet<Character>();
@Override
public synchronized void keyPressed(KeyEvent e) {
pressed.add(e.getKeyChar());
if (pressed.size() > 1) {
// More than one key is currently pressed.
// Iterate over pressed to get the keys.
}
}
@Override
public synchronized void keyReleased(KeyEvent e) {
pressed.remove(e.getKeyChar());
}
@Override
public void keyTyped(KeyEvent e) {/* Not used */ }
}
这篇关于Swing的KeyListener和多个键同时按下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文