我有一个描述我的GUI的fxml。我想改变gui的文本,并在任何地方按任何按键启动任务。使用fxml在Javafx中添加事件监听器到mainScene
FXML
<Text fx:id="barcodeText"/>
控制器
@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应用程序线程内)的barcodeText指针,当我触发事件。
我做错了什么?
我看了看用不用FXML这种方法的例子,我必须使用注释来定义处理器?我在哪里可以在fxml中放置“onAction”场景?
'@FXML Text textBox;'或'@FXML Text barcodeText;'? – pzaenger
FXML加载器在* controller *中初始化'@ FXML'-annotated字段,而不是在调用'start'的'Application'类的实例中。所以'barcodeText'(或者'textBox',或者其他你真正称之为的)在'Application'实例中将是空的。 –
@pzaenger对不起,这是一个错字 –