按键事件未触发
Key press event isn't fired
在一个javaFY项目中,我想给整个添加一个按键监听器window。 window 的 FXML 文件中的根节点是:
<VBox onKeyPressed="#windowKeyPressed" fx:controller="hu.kleni.tetris.EventController" ...>
和 hte 事件处理程序 class:
public class EventController {
@FXML
public void windowKeyPressed(KeyEvent event) {
System.out.println(event.getCode());
}
...
}
在 main()
方法中,它只是加载并启动 window。如果我启动该程序,windows 会出现,但在我按下某个键后,我在控制台中看不到任何内容。我错过了什么吗?
编辑:虽然我可以使用它(而且效果很好):
scene.setOnKeyPressed((event) -> {
// maybe call EventController.windowKeyPressed(event);
})
,我更愿意只在 FXML 文件中定义所有事件处理程序。
您需要 root
(VBox
) 才能专注于 onKeyPressed
工作。
在您的 Application
class 中,requestFocus()
在您的 root
中显示 Stage
之后,例如:
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
root.requestFocus(); // add this, root is the VBox in your case
}
在一个javaFY项目中,我想给整个添加一个按键监听器window。 window 的 FXML 文件中的根节点是:
<VBox onKeyPressed="#windowKeyPressed" fx:controller="hu.kleni.tetris.EventController" ...>
和 hte 事件处理程序 class:
public class EventController {
@FXML
public void windowKeyPressed(KeyEvent event) {
System.out.println(event.getCode());
}
...
}
在 main()
方法中,它只是加载并启动 window。如果我启动该程序,windows 会出现,但在我按下某个键后,我在控制台中看不到任何内容。我错过了什么吗?
编辑:虽然我可以使用它(而且效果很好):
scene.setOnKeyPressed((event) -> {
// maybe call EventController.windowKeyPressed(event);
})
,我更愿意只在 FXML 文件中定义所有事件处理程序。
您需要 root
(VBox
) 才能专注于 onKeyPressed
工作。
在您的 Application
class 中,requestFocus()
在您的 root
中显示 Stage
之后,例如:
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
root.requestFocus(); // add this, root is the VBox in your case
}