I need help to create keyboard shortcuts in my Java program. As can be seen in my code below, I need to have a keyboard shortcut that is Ctrl + T which works properly and prints "test"
, but the shortcut Ctrl + Shift + T does not print "test2"
as expected, nothing happens:
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(
new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
switch (e.getID()) {
case KeyEvent.KEY_PRESSED:
if (e.getKeyCode() == java.awt.event.KeyEvent.VK_T &&
e.getModifiers() == java.awt.event.InputEvent.CTRL_MASK) {
System.out.print("test");
} else if (e.getKeyCode() == java.awt.event.KeyEvent.VK_R &&
e.getModifiers() == java.awt.event.InputEvent.CTRL_MASK &&
e.getModifiers() == java.awt.event.InputEvent.SHIFT_MASK) {
System.out.print("test2");
}
break;
}
return true;
}
}
);
The modifiers of an InputEvent
are a bit field, so you test them using bitwise operations, not simply ==
. But a simpler approach is to use the is*Down()
methods of InputEvent
:
if (e.getKeyCode() == java.awt.event.KeyEvent.VK_R &&
e.isControlDown() && e.isShiftDown()) {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.