Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if the caps lock key is pressed?

Tags:

java

capslock

Alright, before this gets flagged as a possible duplicate, I've already tried the following code:

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

And it is always returning false for me [see below]. Could someone confirm if this is supposed to be working, and I'm misusing it, or if it's known to be broken? If it is in fact broken, does anyone have a better method to use?

EDIT:

Alright, just found out something more. It appears to just return what it was at the begining of my programs launch. If I start the program with it on, it says its on, and vice versa. Here's 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 that's just always printing out whatever it started as

(ex. if I start with caps lock on, even if I toggle it off right after, it prints:

Caps lock is now: ON

Caps lock is now: ON

Caps lock is now: ON

Caps lock is now: ON

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

like image 745
Alex Coleman Avatar asked Aug 18 '12 17:08

Alex Coleman


People also ask

How do you detect Caps Lock key turned on or not?

The getModifierState() method returns true if a modifier is active; otherwise, it returns false . The event. getModifierState('CapsLock') can be used to detect if the caps lock is on.

What happens when the Caps Lock key is pressed on?

Caps Lock ⇪ Caps Lock is a button on a computer keyboard that causes all letters of bicameral scripts to be generated in capital letters. It is a toggle key: each press reverses the previous action.

Why doesn't my Caps Lock button light up?

The problem could be the LED is faulty, or the driver for the keyboard or which provides the LED indicator lights needs reinstall. Try the Keyboard Troubleshooter at Settings > Update & Security > Troubleshoot.


1 Answers

Poking around, I think getLockingKeyState() might be broken.

You could try KeyboardUtils, but it looks like that means you have to carry JNA overhead.

like image 197
Dave Avatar answered Sep 17 '22 04:09

Dave