Reputation: 521
I would like a specific example on how to turn caps lock on if it is off.
I know how to toggle the key, I have been using this:
toolkit.setLockingKeyState(KeyEvent.VK_CAPS_LOCK, Boolean.TRUE);
That will change the state of the key whether it is on or off. But I want to make sure it is on at the beginning of the application.
(The final goal is having the keyboard LEDs flash in certain sequences, which works better if I have a certain starting state.)
Upvotes: 10
Views: 21516
Reputation: 1
Toolkit toolkit = Toolkit.getDefaultToolkit();
robik.keyPress(KeyEvent.VK_SPACE); // PRESS ANY KEY // Any key needs to be pressed
Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_CAPS_LOCK, true);
robik.keyRelease(KeyEvent.VK_SPACE);
Upvotes: 0
Reputation: 175415
You can use getLockingKeyState
to check if Caps Lock is currently set:
boolean isOn = Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
However, it's unnecessary -- setLockingKeyState
doesn't toggle the state of the key, it sets it. If you pass it true
it will set the key state to on regardless of the original state:
Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_CAPS_LOCK, true);
Upvotes: 20
Reputation: 7
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication52;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
/**
*
* @author DSF Inc - Admin
*/
public class JavaApplication52 extends JFrame {
JavaApplication52() {
setLayout(null);
JTextField t = new JTextField();
t.setBounds(0,0,300,20);
add(t);
t.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
boolean isOn = Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
if (isOn == true) {
System.err.println("ON");
} else {
System.err.println("OFF");
}
}
});
setSize(300, 400);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
JavaApplication52 fr = new JavaApplication52();
}
}
Upvotes: 0