0
votes

when i minimize my Stage, JavaFX don't fire my KeyPressed Event. How can i listen to the KeyEvent when the Stage is minimized?

Here i call my Stage:

public void start(Stage primaryStage) throws IOException {
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Gui.fxml"));
    Parent root = fxmlLoader.load();
    primaryStage.setTitle("KillSwitch");
    primaryStage.setScene(new Scene(root));
    primaryStage.getScene().getRoot().requestFocus();
    primaryStage.show();
}

And this is the EventHandler:

public void handleKeyInput(javafx.scene.input.KeyEvent event) throws InterruptedException, SerialPortException, IOException {
    if (event.getCode() == KeyCode.UP) {
        handletriggerButton();
    }
}
1
You can't, at least without using some kind of hook to native code. And do you really want your application to be responding if the user minimizes it and starts typing in their word processor, for example?James_D
@James_D Do you have some Example for the native code? The User should Kalibrate the Programm with the Gui, than minimize it and than controll it with keys.M. Köller
No: I have never done that. But having a visually inactive program responding to arbitrary key presses sounds very dangerous to me - the user is likely to be completely unaware that they are controlling this application in many cases.James_D

1 Answers

0
votes

Most User Interface Toolkits, including JavaFX deliver key events to the currently focussed user interface element, propagating them up until they've reached the root node.

If your window is minimized none of its elements will have the keyboard focus, and thus nobody will receive a key event.

Therefore as @James_D commented you'll need a native hook into the operating system to intercept system wide keyboard event, like e.g. a keylogger does.

For integrating native could you could go the Java Native Interface way, or have some of the rougher edges taken off by a library such as Java Native Access.

On how to do it in your targeted operating system you should probably research that for the operating system itself.