微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavaFx runlater 方法问题,当尝试访问使用 SceneBuilder

如何解决JavaFx runlater 方法问题,当尝试访问使用 SceneBuilder

我在尝试使用 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();
     }
}

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。