M. Köller
M. Köller

Reputation: 1

JavaFX KeyEvent when Stage inactive

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();
    }
}

Upvotes: 0

Views: 588

Answers (2)

Lson
Lson

Reputation: 197

use jnativehook you can listen keyEvent when app in minimize

<dependency>
 <groupId>com.github.kwhat</groupId>
 <artifactId>jnativehook</artifactId>
 <version>2.2.1</version>
</dependency>
public class GlobalKeyListener implements NativeKeyListener {
    
    @Override
    public void nativeKeyPressed(NativeKeyEvent e) {
        // todo something
        System.out.println(e);

    }

    @Override
    public void nativeKeyReleased(NativeKeyEvent e) {
    }

    @Override
    public void nativeKeyTyped(NativeKeyEvent e) {
    }
}


 public static void main(String[] args) {
     //register
        GlobalScreen.registerNativeHook();
        GlobalScreen.addNativeKeyListener(new GlobalKeyListener());
 }

Upvotes: 0

M. le Rutte
M. le Rutte

Reputation: 3563

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.

Upvotes: 0

Related Questions