在IDE中复制以下代码。我用Windows 10,Java 8测试了该代码。
按2键说A(第一个)和B(秒)并按下第一个键,然后快速释放按下的第二个键。按下的第二个键的释放事件将丢失。
如果按下第二个键,它将再次开始生成键重复,然后锁定键释放。
此事件消失实际上搞砸了代码,因为它无法解释错过的发布事件并且状态被搞砸了。这个错误是一种耻辱!!比AWT Linux Key事件错误更糟糕,我找到了一个不错的解决方案。
你看到了解决方案吗?你可以在SWT(可能)中禁用密钥重复吗?
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class SWTKeyEvent {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("SWT KeyEvent Example");
shell.setLayout(new FillLayout());
Button button = new Button(shell, SWT.CENTER);
button.setText("Type Something");
button.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
boolean isKeyRepeat = isKeyRepeat(e.keyCode);
if (!isKeyRepeat) {
System.out.println("\t keyPressed " + e.keyCode);
} else {
System.out.println("keyRepeated " + e.keyCode);
}
}
public void keyReleased(KeyEvent e) {
System.out.println("\t\t keyReleased " + e.keyCode);
keyReleaseRepeat(e.keyCode);
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
protected static int pressedKeyCounter;
protected static int[] pressedKeys = new int[20];
public static boolean isKeyRepeat(int keyCode) {
for (int i = 0; i < pressedKeyCounter; i++) {
if (pressedKeys[i] == keyCode) {
return true;
}
}
pressedKeys[pressedKeyCounter] = keyCode;
pressedKeyCounter++;
return false;
}
public static void keyReleaseRepeat(int keyCode) {
boolean shift = false;
for (int i = 0; i < pressedKeyCounter; i++) {
if (pressedKeys[i] == keyCode) {
shift = true;
} else if (shift) {
pressedKeys[i - 1] = pressedKeys[i];
}
}
if (pressedKeyCounter > 0) {
pressedKeyCounter--;
}
}
编辑:在Swing或JavaFX中,发布事件永远不会丢失