How to check if the cap lock key is pressed?

Well, before this is flagged as a possible duplicate, I already tried the following code:

Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)

And he always gives me a lie [see below]. Can someone confirm that this should work, and I abuse it, or if it is known to have broken? If it is really broken, does anyone have a better method?

EDIT:

Well, just learned something more. It seems to be just returning what was at the beginning of my programs. If I run a program with her, she talks about it, and vice versa. Here is my code:

while (true) {
    boolean isOn = Toolkit.getDefaultToolkit().getLockingKeyState(
        KeyEvent.VK_CAPS_LOCK);
    System.out.println("Caps lock is now: " + (isOn ? "ON" : "off"));
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    }
}

And it always prints everything that started with

(for example, if I start by closing the caps, even if I turn it off right away, it prints:

Now cap lock: ON

Now cap lock: ON

Now cap lock: ON

Now cap lock: ON

etc., if I start with it, it will print no matter what)

+7
3

, , getLockingKeyState() .

KeyboardUtils, , , , JNA.

+3

, , , Java 1.3 (. 4414164).

, Windows : Caps Lock , AWT . , , :

boolean isCapsLockOn() {
    java.awt.Robot robot = new java.awt.Robot();
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    return Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);  
}

: awt isCapsLockOn.

. , . .

0
public void checkOnOff() {
    Thread th = new Thread() {
        public void run() {
            for (;;) {
                if (Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)) {
                    jLabel4.setForeground(Color.red);
                    jLabel4.setText("CAPSLOCK is ON");
                } else {
                    jLabel4.setText(null);
                }
                try {
                    sleep(100);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                }                    
            }
        }
    };th.start();
}
-1
source

All Articles