[英]JavaFx SceneBuilder - Cannot update Label text - NullPointerException
我如何加载它:
public class App extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader();
Parent root = loader.load(new File("src/dreambot/guis/XPTracker.fxml").toURI().toURL());
Controller l = (Controller) loader.getControllerFactory();
primaryStage.setTitle("XP Tracker");
primaryStage.setScene(new Scene(root));
primaryStage.show();
l.setAtkXph(23233);
}
public void build(String[] args) {
launch(args);
}
}
Controller
public class Controller {
@FXML
Label atkXph;
public void setAtkXph(int num) {
atkXph.setText(num + "/h");
}
}
Main(String[] args) 方法
public class Tests {
public static void main(String[] args) {
new App().build(args);
}
}
我的 fxml 中的 label:
<Label id="atkXph" fx:id="atkXph" layoutX="68.0" layoutY="71.0" text="0/h" />
我的错误:
Exception in Application start method
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$159(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
at dreambot.main.App.start(App.java:23)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$166(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$179(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$177(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$178(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$152(WinApplication.java:177)
... 1 more
Controller 和 controller 工厂是两个不同的东西:
controller 是 object 包含与#methodName
属性值和加载程序基于fx:id
注入对象的字段一起使用的方法。
controller 工厂用于创建 controller,如果您为其分配一个。
controllerFactory.call(Class.forName(<fx:controller attribute value>))
如果在加载 fxml 之前分配Callback
,则 FXMLLoader 使用FXMLLoader
来创建 controller class 的实例。
此外,您使用static
load
方法之一。 这样,您无法访问的第二个FXMLLoader
实例将被创建并用于加载 fxml。 在加载 fxml 之前,您需要指定URL
作为位置。
FXMLLoader loader = new FXMLLoader(new File("src/dreambot/guis/XPTracker.fxml").toURI().toURL()); // maybe replace with resource access (getClass().getResource("/dreambot/guis/XPTracker.fxml"))?
Parent root = loader.load();
Controller l = loader.getController();
此外,您不能自己创建Application
class 的实例并使用标准启动方式。 Application.launch
总是创建应用程序 class 的新实例。 在这种情况下, build
方法static
将用于相同的目的,但您也可以使用重载版本的launch
指定应用程序 class :
Application.launch(App.class, args);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.