我在Eclipse中创建了一个使用JavaFx和MVC模式的简单计算器。我想添加keylisteners,只需按下键盘上的按钮即可按下计算器的按钮。我试图在SceneBuilder中添加#onKeyPress,然后在我的Controller类中添加一个onKeypress方法(里面有一些编码),但没有任何反应。请你给出一些如何实现这样的通用指令?谢谢!
答案 0 :(得分:0)
感谢您的评论。我在App.java中添加了以下代码片段:
scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
controller.numFromKeyboard(event.getCode().toString());
}
});
而且,我必须补充:
Parent root = loader.load();
Controller controller = loader.getController();
// The above line MUST be
// inserted after root is loaded in order the controller of my
// app to be instantiated,
// otherwise we will get a null exception when handler will be
// invoked
<强> App.java 强>
public class App extends Application {
//controller = new Controller();
@Override
public void start(Stage primaryStage) {
try {
// Read file fxml and draw interface.
FXMLLoader loader = new FXMLLoader(getClass()
.getResource("/application/View.fxml"));
Parent root = loader.load();
Controller controller = loader.getController();
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("/application/application.css").toExternalForm());
Image icon = new Image(getClass().getResourceAsStream("/application/Assets/App.png"));
primaryStage.getIcons().add(icon);
primaryStage.setTitle("JavaFX Calculator by Dimitris Baltas");
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
controller.numFromKeyboard(event.getCode().toString());
}
});
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}