如何在不显示框架的情况下以便携式方式检查 Java 中的 NUM LOCK 键状态?
我想在运行时知道 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论