Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine modifier key state without an InputEvent object in Java

Tags:

java

keyboard

awt

I need to determine the current state of the Shift key, but at the time I need the state I don't have an InputEvent object around. I need something like java.awt.Toolkit.getLockingKeyState(int) that works for Shift, not just the locking keys like VK_CAPS_LOCK. Is there a way I can do this without listening to input events and storing the for later when I need to check the state?

Thanks!

like image 731
heycam Avatar asked Jun 16 '10 01:06

heycam


1 Answers

I don't think it is possible to get the status of the Shift key if you don't have an Event in hand. Even java.awt.Toolkit.getLockingKeyState(int) uses native code to get its information. I'm sure you could devise your own event tracker/store, etc, but just in case, here is a small method that could be usefull. You must provide it with an AWT Component that has the focus.

public static boolean isShiftDown(Component c) throws AWTException {
    final List<Boolean> res = new ArrayList<Boolean>();
    final KeyListener listener = new KeyAdapter() {
        @Override public void keyReleased(KeyEvent e) {
            res.add(e.isShiftDown());
        }
    };
    c.addKeyListener(listener);
    new Robot().keyRelease(KeyEvent.VK_ALT);
    try {Thread.sleep(50);} catch (InterruptedException e) {}
    c.removeKeyListener(listener);
    if (res.size() > 0)
        return res.get(0);
    throw new AWTException("Could not get shift key status.");
}
like image 114
solendil Avatar answered Oct 17 '22 16:10

solendil