JavaFx-当fxml注入对象字段? [英] JavaFx-when fxml inject object field?
问题描述
我是javaFx的新手,我只在@fxml函数和初始化函数中找到@fxml字段不为null,否则@fxml字段将始终为null,是真的吗?
如果是这样,我如何在加载fxml(不使用查找)之后立即使用@fxml字段,就像这样?(代码跟随将抛出一个空异常)
I'm new to javaFx,and I have found only within the @fxml function and initialize function the @fxml field not be null otherwise the @fxml field will always be null,is it true? If so,how can i use a @fxml field immediately after i load a fxml(do not use lookup),just like this?(the code follow will throw a null exception)
@FXML Label resultTF;
....
FXMLLoader loader=new FXMLLoader();
loader.setController(this);
Parent pane = loader.load(getClass().getResource("/fxml/Main.fxml"));
this.resultTF.setText("");
我想做的就是在fxml中声明一个id为id的字段,并在之后立即使用它加载fxml,类似于wpf,flex
All i want to do is to declare a field with id in the fxml,and use it immediately after load the fxml,something like wpf,flex
推荐答案
您正在调用静态 FXMLLoader.load(URL)
方法。
You are calling the static FXMLLoader.load(URL)
method.
由于它是一个静态方法,它对你用来调用它的实例一无所知(无论如何这都是不好的做法) ;您的IDE应该发出关于此的警告)。具体来说,它没有控制器设置。
Since it's a static method, it knows nothing about the instance you are using to invoke it (which is bad practice anyway; your IDE should issue a warning about this). Specifically, it doesn't have a controller set.
您需要调用 instance load()
方法,例如
You need to invoke an instance load()
method, e.g.
FXMLLoader loader=new FXMLLoader();
loader.setController(this);
loader.setLocation(getClass().getResource("/fxml/Main.fxml"));
Parent pane = loader.load();
这篇关于JavaFx-当fxml注入对象字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!