How can I read the status of the Caps Lock key?

Jorge Jordão

Maybe this isn't the "cleanest" solution, but it works.

Assuming you'll have an AWT component visible (a Frame for instance) and you're using JDK 1.3:

  • Handle the component keyPressed event and, using Character.isUpperCase, determine whether the caracter generated is upper case.
  • To automate the process, use the (new) java.awt.Robot class to generate a "simple caracter" key press (for instance KeyEvent.VK_A).
Example: (try executing it with and without Caps Lock)
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);	
	
    }

}
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact