如何在不显示框架的情况下以便携式方式检查 Java 中的 NUM LOCK 键状态?

发布于 2024-12-26 12:30:44 字数 1287 浏览 2 评论 0原文

我想在运行时知道 NUM LOCK 或 CAPS LOCK 键是打开还是关闭。但我需要以可移植的方式做到这一点(对于所有 Java 平台)。

以下两种方法不起作用:

1) 它会抛出 UnsupportedOperationException: Toolkit.getLockingKeyState under Linux with OpenJDK-6:

Toolkit toolkit = Toolkit.getDefaultToolkit();
boolean numlock = toolkit.getLockingKeyState(KeyEvent.VK_NUM_LOCK);

2) 它显示一个 Frame,但我们需要在不显示工件的情况下执行此操作(找到的想法 此处):

import java.awt.*;
import java.awt.event.*;

public class Test {

    public static void main(String[] args) throws AWTException {

        // create AWT component
        Frame f = new Frame();
        // handle component's keyPressed event
        f.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent ev) {
                System.out.println(Character.isUpperCase(
                  ev.getKeyChar()) ? 
                    "Caps Lock ON" : 
                    "Caps Lock OFF");
            }       
        });
        // make component visible (otherwise the Robot won't work)
        f.show();
        // create Robot
        Robot robot = new Robot();
        // generate simple caracter key press
        robot.keyPress(KeyEvent.VK_A);  

    }

}

I want to know at runtime if the NUM LOCK or the CAPS LOCK key is on or off. But I need to do that in a portable way (for all Java platforms).

The following two methods don't work:

1) It throws UnsupportedOperationException: Toolkit.getLockingKeyState under Linux with OpenJDK-6:

Toolkit toolkit = Toolkit.getDefaultToolkit();
boolean numlock = toolkit.getLockingKeyState(KeyEvent.VK_NUM_LOCK);

2) It displays a Frame, but we need to do that without displaying artifacts (idea found here):

import java.awt.*;
import java.awt.event.*;

public class Test {

    public static void main(String[] args) throws AWTException {

        // create AWT component
        Frame f = new Frame();
        // handle component's keyPressed event
        f.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent ev) {
                System.out.println(Character.isUpperCase(
                  ev.getKeyChar()) ? 
                    "Caps Lock ON" : 
                    "Caps Lock OFF");
            }       
        });
        // make component visible (otherwise the Robot won't work)
        f.show();
        // create Robot
        Robot robot = new Robot();
        // generate simple caracter key press
        robot.keyPress(KeyEvent.VK_A);  

    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文