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
InputEventare a bit field, so you test them using bitwise operations, not simply==. But a simpler approach is to use theis*Down()methods ofInputEvent: