Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

swing - How to check for key being held down on startup in Java

I'm trying to write a resolution selection dialog that pops up when a program first starts up. To prevent boring the user, I want to implement the fairly standard feature that you can turn off that dialog with a checkbox, but get it back by holding down the alt key at startup.

Unfortunately, there is no obvious way to ask java whether a given key is currently being pressed. You can only register to be informed of new key presses via a KeyListener, but that doesn't help if the keypress starts before the app launches.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;

public class LockingKeyDemo {
    static Toolkit kit = Toolkit.getDefaultToolkit();

    public static void main(String[] args) {
        JFrame frame = new JFrame();

        frame.addWindowListener(new WindowAdapter() {
            public void windowActivated(WindowEvent e) {
                System.out.println("caps lock1 = "
                        + kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));

                try {
                    Robot robot = new Robot();
                    robot.keyPress(KeyEvent.VK_CONTROL);
                    robot.keyRelease(KeyEvent.VK_CONTROL);
                } catch (Exception e2) {
                    System.out.println(e2);
                }

                System.out.println("caps lock2 = "
                        + kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));
            }
        });

        frame.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                System.out.println("caps lock3 = "
                        + kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));
            }
        });

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...