user9959339
user9959339

Reputation:

how to get KeyEvent handled in javafx

I have tests about KeyEvent in javafx,if I use onKeyPressed() method bound to any kind of pane,it wouldn't work.bound to scene or a button would work fine.I am wondering how can I let pane associated with KeyEvent.

Upvotes: 1

Views: 574

Answers (1)

Przemek Krysztofiak
Przemek Krysztofiak

Reputation: 924

To add key events handlers to pane effectively you need to request focus on pane first.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class PanesKeyEventsApp extends Application {

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

    @Override
    public void start(Stage stage) throws Exception {

        StackPane stackPane1 = new StackPane();
        stackPane1.setPrefSize(200, 200);
        stackPane1.setStyle("-fx-background-color: purple;");

        StackPane stackPane2 = new StackPane();
        stackPane2.setPrefSize(200, 200);
        stackPane2.setStyle("-fx-background-color: yellow;");

        HBox hBox = new HBox(stackPane1, stackPane2);

        Scene scene = new Scene(hBox);
        stage.setScene(scene);
        stage.show();

        stackPane1.setOnMouseClicked(event -> stackPane1.requestFocus());
        stackPane2.setOnMouseClicked(event -> stackPane2.requestFocus());

        stackPane1.addEventHandler(KeyEvent.KEY_PRESSED, event -> System.out.println("purple key pressed " + event.getCode()));
        stackPane2.addEventHandler(KeyEvent.KEY_PRESSED, event -> System.out.println("yellow key pressed " + event.getCode()));
    }
}

Upvotes: 2

Related Questions