Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I check the status of the CAPS and NUM lock keys?

Starting out with Java

How do I check the status of the CAPS and NUM lock keys?

by  Ghodmode  Posted    (Edited  )
Code:
import java.awt.*;
import java.awt.event.*;

/**
 * This class is an example of one method for checking the
 * state of the CAPS and NUM lock keys before a KeyEvent has
 * been generated.  On some platforms, the
 * Toolkit.getLockingKeyState() method is not supported and
 * throws an UnsupportedOperationException.  The hack
 * creates a new java.awt.Frame, generates some appropriate
 * KeyEvents using java.awt.Robot to be received by an
 * anonymous inner class.  After the hack does it's job, the
 * Frame is disposed to release the memory.
 */
public class capstest {
	public static void main( String [] args ) {
		Frame frame = new Frame( "Checking Locking Key State ..." );

		frame.addKeyListener( new KeyAdapter() {
			public void keyPressed( KeyEvent e ) {
				if ( Character.isLetter(e.getKeyChar()) ) {
					if ( Character.isUpperCase(e.getKeyChar()) )
						System.out.println( "CAPS Lock is On" );
				} else {
					if ( Character.isDigit(e.getKeyChar()) )
						System.out.println( "NUM Lock is on" );
				}
			}
		});

		// If the frame isn't set visible, the key presses
		// go to the console rather than to the frame
		frame.setVisible( true );

		try {
			Robot robot = new Robot();
			robot.keyPress( KeyEvent.VK_A );
			robot.keyRelease( KeyEvent.VK_A );

			robot.keyPress( KeyEvent.VK_NUMPAD5 );
			robot.keyRelease( KeyEvent.VK_NUMPAD5 );
			frame.dispose();
		} catch ( AWTException e ) {
		}
	}
}
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top