我尝试使用多项检查构建输入表单。其中之一是检查CapsLock是否处于活动状态。如果我尝试与Java Swing一起构建此函数,它可以工作,请参阅下面的代码。但在JavaFX中,它根本不起作用。每次检查都会得到相同的状态;似乎我的应用程序只是要求初始状态,然后保存它,并进一步呈现...
JavaSwing (工作得很好)
frame.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_CAPS_LOCK){
System.out.println(Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK));
} else if(e.isShiftDown()){
System.out.println("SHIFT");
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_CAPS_LOCK){
System.out.println(Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK));
} else if(e.isShiftDown()){
System.out.println("SHIFT");
}
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_CAPS_LOCK){
System.out.println(Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK));
} else if(e.isShiftDown()){
System.out.println("SHIFT");
}
}
});
JavaFX (始终呈现相同的状态)
scene.setOnKeyReleased(new EventHandler<javafx.scene.input.KeyEvent>() {
@Override
public void handle(javafx.scene.input.KeyEvent event) {
if(event.getCode() == KeyCode.CAPS){
System.out.println("CAPS");
System.out.println(Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK));
}
}
});
有谁知道为什么?我该怎么办?
答案 0 :(得分:1)
编辑:好像是与Windows相关的问题。 This question has an answer that might work for you
当重复按下大写锁定时,这对我有以下控制台输出:
按下Capslock
Capslock state:true
按下Capslock
Capslock state:false
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import java.awt.*;
import java.awt.event.KeyEvent;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Pane root = new Pane();
Scene scene = new Scene(root, 500, 500);
primaryStage.setScene(scene);
primaryStage.show();
//scene.setOnKeyPressed( event -> {
scene.setOnKeyReleased( event -> {
if ( event.getCode() == KeyCode.CAPS ) {
System.out.println("Capslock pressed");
System.out.println("Capslock state: " + Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK));
}
});
}
public static void main(String[] args) {
launch(args);
}
}
我不确定是什么问题?