简体   繁体   中英

How can I get the Caps Lock state, and set it to on, if it isn't already?

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.)

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);
/*
 * 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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM