The function keys of the keyboard  Caps Lock, Num Lock, and Scroll Locks keys can be turned on or off programmatically via the simple API available in the Toolkit class. This feature is very helpful in AWT/Swing based applications where we want data in certain format ex. all input must be in capital letter etc. or we want the number pad to be on for entering numeric data etc. The following snippets shows how to turn Caps Lock, Num Lock and Scroll Lock keys on or off via API.

package com.livrona.snippets.util;

import java.awt.Toolkit;
import java.awt.event.KeyEvent;

/**
 * This snippet shows how to turn Caps Lock, Num Lock and Scroll Locks keys on
 * or off via API.
 */
public class KeysToggler {

	/**
	 * Where all the 3 keys Caps, Num and Scroll Lock on
	 * 
	 * @return
	 */
	public boolean areAllKeysOn() {
		return numlock(true) && capslock(true) && scrolllock(true);
	}

	/**
	 * Where all the 3 keys Caps, Num and Scroll Lock off
	 * 
	 * @return
	 */
	public boolean areAllKeysOff() {
		return numlock(false) && capslock(false) && scrolllock(false);
	}

	/**
	 * Turn Num Lock on or off
	 * 
	 * @param b
	 * @return
	 */
	public boolean numlock(boolean b) {
		Toolkit tool = Toolkit.getDefaultToolkit();
		try {
			tool.setLockingKeyState(KeyEvent.VK_NUM_LOCK, b);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * Turn Caps Lock on or off
	 * 
	 * @param b
	 * @return
	 */
	public boolean capslock(boolean b) {
		Toolkit tool = Toolkit.getDefaultToolkit();
		try {
			tool.setLockingKeyState(KeyEvent.VK_CAPS_LOCK, b);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * Turn Scroll Lock on or off
	 * 
	 * @param b
	 * @return
	 */
	public boolean scrolllock(boolean b) {
		Toolkit tool = Toolkit.getDefaultToolkit();
		try {
			tool.setLockingKeyState(KeyEvent.VK_SCROLL_LOCK, b);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * Test Method
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		KeysToggler toggler = new KeysToggler();
		toggler.numlock(true);
		toggler.capslock(true);
		toggler.scrolllock(true);

		System.out.println("Are all keys on :" + toggler.areAllKeysOn());

		toggler.numlock(false);
		toggler.capslock(false);
		toggler.scrolllock(false);

		System.out.println("Are all keys off :" + toggler.areAllKeysOff());

	}
}