我有一个描述我的 gui 的 fxml。我想更改 gui 的文本并在任何地方按任意键启动任务。
FXML
<Text fx:id="barcodeText"/>
Controller
@FXML
Text barcodeText;
public void start(Stage primaryStage) throws IOException {
this.primaryStage=primaryStage;
Scene mainScene =new Scene(root);
primaryStage.setScene(mainScene);
primaryStage.setResizable(false);
primaryStage.show();
Parent root = FXMLLoader.load(getClass().getResource("/view/foo.fxml"));
mainScene.addEventHandler(KeyEvent.KEY_PRESSED,new KeyboardEventHandler(){
@Override
public void handle(KeyEvent event) {
barcodeText.setText("foo");
}
});
当我触发事件时,这会给我一个条形码文本指针的NullPointerException
(在JavaFX应用程序线程内)。
我做错了什么吗?
我查看的示例使用的是这种没有 fxml 的方法,我是否必须使用注释来定义处理程序?我应该在 fxml 中的哪里放置场景的“onAction”?
最佳答案
(旁白:看起来您正在尝试对 Controller 和应用程序使用相同的类。Don't do that.)
在 Controller 类中定义一个方法来设置条形码文本:
public void setBarcodeText(String barcode) {
barcodeText.setText(barcode);
}
然后从您的处理程序中调用该方法:
FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/foo.fxml"));
Parent root = loader.load();
MyControllerClass controller = loader.getController();
Scene mainScene = new Scene(root);
mainScene.addEventHandler(KeyEvent.KEY_PRESSED, new KeyboardEventHandler(){
@Override
public void handle(KeyEvent event) {
controller.setBarcodeText("foo");
}
});
显然,将 MyControllerClass
替换为 Controller 类的实际名称。
关于java - 使用 fxml 将事件监听器添加到 Javafx 中的 mainScene,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42512513/