I'm programming an application which should, when started, check whether the shift key is pressed. For that I have created a small class which is responsible for that:
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
public class KeyboardListener {
private static boolean isShiftDown;
static {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(
new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
isShiftDown = e.isShiftDown();
return false;
}
});
}
public static boolean isShiftDown() {
return isShiftDown;
}
}
However, it seems that this is not working if the shift key was already pressed when the application started up. The following check always executes the else case.
if (KeyboardListener.isShiftDown()) {
// ...
} else {
// this always gets executed
}
Is there a way of checking whether the shift key is pressed if it was already pressed when the application started? I know this is possible using WinAPI, but I would prefer a Javaish way of doing it.
Thanks in advance!
It does not seem possible, since it requires the application to poll for the initial status, opposed to the model of events used by AWT/Swing.