I have problem with FXML and keyPress handler.
I try to set on key press simple test, but the key handler is not called. Mouse handling, etc works correctly, but keys handling does not.
I tried to setKeyHandler on Pane, circle (in Pane) and scene.
public class Controller implements Initializable {
public Pane canvas;
public Label yDisplay;
public Label xDisplay;
public Circle circle;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
canvas.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent keyEvent) {
System.out.println("Test");
}
});
}
}
Respected Dil, thx for your answer, but i want did some "game", where simple circle on pane, moved by press on keybord. Of course, with focus on compmonent will work. But whithout focus. Maybe key listener must be set on window or scene? I apologize for the vagueness of purpose.
I tried to set on press, but scence, in Initialization, is null.
public class Controller implements Initializable {
@FXML private Pane canvas;
@FXML private Label yDisplay;
@FXML private Label xDisplay;
@FXML private Circle circle;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
canvas.getScene().setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent keyEvent) {
System.out.println("Work");
}
});
canvas.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
canvas.getChildren().add(new Bullet(150.0, 150.0, mouseEvent.getX(), mouseEvent.getY()));
}
});
}
}
It's logic, and i tried to set in Apllication class. Set key handler on Application, and it's work! But, how to get Circle and other component of scene, becouse they kepp in controlle.class
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root));
primaryStage.getScene().setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent keyEvent) {
System.out.println("HEY");
}
});
primaryStage.show();
}
Right now i tied do it with lookup of scence / Parent root
Yes! lookup of Parent is work. I just must to search by # + "id"
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root));
primaryStage.getScene().setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent keyEvent) {
System.out.println("HEY");
Circle myCirecle = (Circle) root.lookup("#circle");
myCirecle.setTranslateY(10.0);
}
});
primaryStage.show();
}