Determine modifier key state without an InputEvent object in Java
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 inp开发者_如何学编程ut events and storing the for later when I need to check the state?
Thanks!
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.");
}
精彩评论