java - 尝试访问使用 SceneBuilder 生成的 FXML 时出现 JavaFx runlater 方法问题
问题描述
我在尝试使用 runLater() 以异步方式修改使用 SceneBuilder 创建的 JavaFx 标签时遇到问题。
我可以从按钮触发的回调中修改它,但是当我尝试从 runLater 方法访问相同的元素时,我收到一个错误,指出该元素为空。
错误代码:
jun 30, 2021 3:42:25 P. M. javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 16 by JavaFX runtime of version 11.0.2
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Cannot invoke "javafx.scene.control.Label.setText(String)" because "this.texto" is null
at test.view.GuiApp.lambda$0(GuiApp.java:58)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
at java.base/java.lang.Thread.run(Thread.java:831)
我的代码:
public class GuiApp extends Application{
private Region rootLayout;
private Stage stage;
@FXML private Pane tankPane;
@FXML public Label texto ;
public static GuiApp main;
@Override
public void start(Stage primaryStage) throws IOException {
main = this;
stage = primaryStage;
stage.setTitle("mainStage");
stage.setResizable(false);
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(GuiApp.class.getResource("main.fxml"));
rootLayout = (Region) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
stage.setScene(scene);
stage.show();
Platform.runLater(() -> texto.setText("klfdsfklañsd"));
}
public static void main(String[] args) {
launch(args);
}
@FXML
public void updateRandom()
{
Random r = new Random();
texto.setText(Float.toString(r.nextFloat()));
}
@FXML
private void onReload() {
updateRandom();
}
}
我试图将其简化为最简单的,顺便说一句对不起我的英语。
解决方案
推荐阅读
- spring-data - 使用 spring-data-envers 查询嵌套对象的修订
- python - Matplotlib 挤压 x 标签
- javascript - Datatables 1.9.4: data-order attribute is ignored
- javascript - React useState setter 不会更新上下文中的值
- assembly - ARM 32bit - 将 4 字节浮点数移动到寄存器
- reactjs - 如何在本机反应中将字符串转换为代码?
- c++ - 为什么赋值表达式中的重叠必须是精确的并且对象必须具有相同的类型,这是什么意思?
- python - 为什么这个 for 循环在每个循环上附加相同的值?
- ios - 删除了 Xcode 中的通知扩展,现在应用程序将无法构建
- javascript - 将 Excel.Application COMObject 与 Javascript 和 Spidermonkey 一起使用的问题(在 Sparx EA 中)