首页 > 解决方案 > JAVA FX - 如何从窗格中删除对象?

问题描述

我正在尝试使用 java fx 添加一个项目。在这个项目中,我有一个堆栈窗格,其中包含一个带有所有控件的 AnchorPane,顶部有一个空的 VBox。

当我调用远程 API 时,需要一段时间才能响应,我在 VBox 上加载了 ProgressIndicator。这工作正常,但在我从 API 获得答案的那一刻,我尝试从 VBox 中删除 ProgressIndicator,但我得到了一个异常:

Exception in thread "OkHttp Dispatcher" java.lang.IllegalStateException: Not on FX application thread; currentThread = OkHttp http://api.kiwandafood.betas.bolboretapps.com/...
    at com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:279)
    at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:444)
    at javafx.scene.Parent$2.onProposedChange(Parent.java:367)
    at com.sun.javafx.collections.VetoableListDecorator.remove(VetoableListDecorator.java:329)
    at com.sun.javafx.collections.VetoableListDecorator.remove(VetoableListDecorator.java:221)
    at com.kiwandalabs.forklift.view.MainOverviewController.setLoading(MainOverviewController.java:536)
    at com.kiwandalabs.forklift.model.Cloud$3.onResponse(Cloud.java:223)
    at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

这是我得到异常的代码,在我从 VBox 中删除 ProgressIndicator 的那一行:

public void setLoading(boolean set) {
        if (set) {
            //Activar
            pi = new ProgressIndicator();
            loadingBox.getChildren().add(pi);
            layoutPrincipal.setDisable(true);
            //System.out.println(stackPrincipal.getChildren().indexOf(loadingBox));
        }else {
            //Desactivar
            layoutPrincipal.setDisable(false);
            loadingBox.getChildren().remove(pi);
            pi = null;
        }
} //End setLoading

标签: javafxml

解决方案


您需要在 FX 应用程序线程上执行操作,例如

javafx.application.Platform.runLater(new Runnable(){
    //  TODO: update UI components here
});

编辑:另外,我的猜测是,在添加进度指示器时,您处于适当的线程中。


推荐阅读