简体   繁体   中英

JavaFX global keyboard listener

I have a JavaFX application which requires the listening of a ctrl+space+T to bring the application window to the front when the application is in the background or minimized. May I know if anyone has a solution to it?

public class MainApp extends Application {

@Override
public void start(Stage primaryStage) {
    primaryStage = setStagePositionToBottomRight(primaryStage);
    loadAndStartMainScreen(primaryStage);
}

private void loadAndStartMainScreen(Stage primaryStage) {
    MainViewController scenes = new MainViewController();
    AnchorPane mainScene = scenes.getMainView();
    Scene scene = new Scene(mainScene);
    primaryStage.setScene(scene);
    primaryStage.show();

}



private Stage setStagePositionToBottomRight(Stage primaryStage) {
    final int coordinateX = 335;
    final int coordinateY = 510;

    Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();
    // primaryStage.initStyle(StageStyle.UNDECORATED);
    primaryStage.setX(primaryScreenBounds.getMaxX() - coordinateX);
    primaryStage.setY(primaryScreenBounds.getMaxY() - coordinateY);

    return primaryStage;

}

public static void main(String[] args) {
    launch(args);
}
}

I think your requirement can't be implemented in pure java, you'll need some native code to accomplish this.

If you don't want do write everything on your own and your application is running on windows you can take a look at JIntellitype that offers global hotkey functionality.

For anyone having a similar problem:

By listening to all userinputs, you can simply listen for the wanted key-combination, but this requires additional libraries. Thought this is not a good solution, it's a working one.

Link #1: about global eventlisteners in Java and the source of Link #2

Listening for input without focus in Java

Link #2: a library with the needed functions for Windows, Linux, MacOS X

https://github.com/kwhat/jnativehook

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM