首页 > 解决方案 > 尝试访问使用 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();
     }
}

我试图将其简化为最简单的,顺便说一句对不起我的英语。

标签: javajavafxscenebuilder

解决方案


推荐阅读