How to check NUM LOCK key state in Java in a portable way without displaying a frame?

2k views Asked by At

I want to know at runtime if the NUM LOCK or the CAPS LOCK key is on or off. But I need to do that in a portable way (for all Java platforms).

The following two methods don't work:

1) It throws UnsupportedOperationException: Toolkit.getLockingKeyState under Linux with OpenJDK-6:

Toolkit toolkit = Toolkit.getDefaultToolkit();
boolean numlock = toolkit.getLockingKeyState(KeyEvent.VK_NUM_LOCK);

2) It displays a Frame, but we need to do that without displaying artifacts (idea found here):

import java.awt.*;
import java.awt.event.*;

public class Test {

    public static void main(String[] args) throws AWTException {

        // create AWT component
        Frame f = new Frame();
        // handle component's keyPressed event
        f.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent ev) {
                System.out.println(Character.isUpperCase(
                  ev.getKeyChar()) ? 
                    "Caps Lock ON" : 
                    "Caps Lock OFF");
            }       
        });
        // make component visible (otherwise the Robot won't work)
        f.show();
        // create Robot
        Robot robot = new Robot();
        // generate simple caracter key press
        robot.keyPress(KeyEvent.VK_A);  

    }

}
0

There are 0 answers