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.
当同时按两个键盘键时,是否有常规的跟踪事件的方法?我有一些想法,比如记住关键和事件生成时间,这样我们就可以在一个连续的事件处理程序调用中检查这两个事件之间的时间差,并决定它是否为两个按钮事件。但它看起来像一个组装机器。
2 个解决方案
#1
15
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 */ }
}
#2
2
The KeyListener interface allows detecting key pressing and releasing separately. Therefore, you can maintain a set of "active keys", i.e. keys which have been pressed but not released yet.
KeyListener接口允许检测关键的压缩和释放。因此,您可以维护一组“活动键”,即已按下但尚未释放的键。
#1
15
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 */ }
}
#2
2
The KeyListener interface allows detecting key pressing and releasing separately. Therefore, you can maintain a set of "active keys", i.e. keys which have been pressed but not released yet.
KeyListener接口允许检测关键的压缩和释放。因此,您可以维护一组“活动键”,即已按下但尚未释放的键。