javafx keyboard event shortcut key
Asked Answered
Q

4

9

I want to add keyboard shortcut key in javafx.

i have scene and want to implement the keyboard shortcut

my code is as follows

getApplication().getScene().setOnKeyPressed(new EventHandler<KeyEvent>() {

        public void handle(KeyEvent ke) {
            if (ke.getCode() == KeyCode.ESCAPE) {
                System.out.println("Key Pressed: " + ke.getCode());
            }
        }
    });
Quiz answered 20/8, 2014 at 6:5 Comment(5)
Where is the problem ?Kantian
my scene is getApplication().getScene() and i am not getting key event in thisQuiz
What is getApplication() doing ? Is it returning an instance of your Application ? Can you post a SSCCE depicting your problem ?Kantian
Are you looking for a global shortcut key (a key that works in all locations in your application) or a key that operates in a narrower scope?Grenoble
yes i am looking for that kind of shortcut keyQuiz
L
23

Events travel from the scene to the focused node (event capturing) and then back to the scene (event bubbling). Event filter are triggered during event capturing, while onKeyPressed and event handler are triggered during event bubbling. Some controls (for example TextField) consume the event, so it never comes back to the scene, i.e. event bubbling is canceled and onKeyPressed for the scene doesn't work.

To get all key pressed events use addEventFilter method:

scene.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
    public void handle(KeyEvent ke) {
        if (ke.getCode() == KeyCode.ESCAPE) {
            System.out.println("Key Pressed: " + ke.getCode());
            ke.consume(); // <-- stops passing the event to next node
        }
    }
});

If you want to capture key combinations use the KeyCodeCombination class:

scene.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
    final KeyCombination keyComb = new KeyCodeCombination(KeyCode.ESCAPE,
                                                          KeyCombination.CONTROL_DOWN);
    public void handle(KeyEvent ke) {
        if (keyComb.match(ke)) {
            System.out.println("Key Pressed: " + keyComb);
            ke.consume(); // <-- stops passing the event to next node
        }
    }
});

There is also the possibility to add shortcuts to the menu by setting an accelerator (see [2]).

References

Ligetti answered 30/10, 2016 at 13:9 Comment(0)
K
2

I am not sure what you are doing with getApplication, but just to show that KeyEventHandler on Scene works, here's a demo for you.

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class MyApp extends Application {
    public void start(Stage stage) {

        VBox root = new VBox();
        root.setAlignment(Pos.CENTER);
        Label heading = new Label("Press Key");
        Label keyPressed = new Label();
        root.getChildren().addAll(heading, keyPressed);
        Scene scene = new Scene(root, 400, 300);

        scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
            public void handle(KeyEvent ke) {
                keyPressed.setText("Key Pressed: " + ke.getCode());
            }
        });

        stage.setTitle("My JavaFX Application");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
Kantian answered 21/8, 2014 at 8:14 Comment(1)
You can get the Scene of a controller either with giving it an fx:id or take a component of the scene of your choice and do myComponent.getScene(). Or you can set the onKeyPressed property/method/action of the scene in the fxml file (or via SceneBuilder).Composite
M
1

I just started learning javaFX so hope that help someone like me out there :)

Here is an example of key combination of how to exit from the app. You can perform any action you want.

1st, init a controller (could be a button or menu item)

MenuItem quit = new MenuItem("Quit");

2nd, set event handler

quit.setOnAction(new EventHandler() {
   @Override public void handle(ActionEvent e) {
     //  quit/close app
     primaryStage.close();
   }
});

and then setAccelerator to perform an action

quit.setAccelerator(new KeyCodeCombination(KeyCode.E, KeyCombination.CONTROL_DOWN));

here is a detail tutorial

https://blog.idrsolutions.com/2014/04/tutorial-how-to-setup-key-combinations-in-javafx/

Hope that helps :)

Medusa answered 14/5, 2020 at 20:11 Comment(0)
K
0

Here is an example for an button but of course it deepends on your target.

private void setSaveAccelerator(final Button button, final KeyCodeCombination keyCodeCombination) {
if (button == null) {
    throw new IllegalArgumentException("button cannot be null");

Scene scene = button.getScene();
if (scene == null) {
    throw new IllegalArgumentException("setSaveAccelerator must be called when a button is attached to a scene");
}

scene.getAccelerators().put(keyCodeCombination, 
// referance of the fire methode of the button, which is a runable 
button::fire);
}
Kamila answered 15/6 at 4:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.