Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving current capslock state in Java [duplicate]

Tags:

java

Using the following code:

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

Unfortunately, only returns false.

As per docs, this should work: http://docs.oracle.com/javase/8/docs/api/java/awt/Toolkit.html#getLockingKeyState-int-

Runnable example:

import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class Foo {

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(1);

        executorService.execute(new Runnable() {
            public void run() {
                while(true) {
                    try{ Thread.sleep(250); }catch(Exception ignored) { }
                    System.out.println("Capslock state: " + Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK));
                }
            }
        });

        executorService.shutdown();
    }

}

Should add that I'm using Java SE 1.8 on Windows and that my Caplock key works fine

Screenshot of console output:

enter image description here

like image 265
Hobbyist Avatar asked Dec 30 '14 06:12

Hobbyist


1 Answers

Your code works fine for me. I just cut pasted your code, compiled it, ran it, and hit caps lock while it was running. Here was the output:

$ javac Foo.java
$ java Foo
Capslock state: false
Capslock state: false
Capslock state: false
Capslock state: false
Capslock state: true
Capslock state: true
Capslock state: true
Capslock state: true
Capslock state: true
Capslock state: true
Capslock state: true
Capslock state: true
Capslock state: false
Capslock state: false
Capslock state: false
^C

I'm using java 8, like you.

$ java -version
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)

Is your caps lock key working?

like image 194
Asaph Avatar answered Oct 27 '22 00:10

Asaph