在 JavaFX 中在后台执行任务 [英] Execute task in background in JavaFX

查看:42
本文介绍了在 JavaFX 中在后台执行任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个 TilePane 中加载最多九个面板.对于每个窗格,我必须首先计算内容(大约 300 毫秒),然后我必须构建面板(大约 500 毫秒).

I want to load up to nine panels in a TilePane. For each pane I have to first run a computation of the content (about 300ms) and then I have to build the Panel (about 500ms).

我想要的是,有九个 ProgressIndicators 在计算后与每个面板交换.

What I want is, that there are nine ProgressIndicators which exchanges with every panel after its computation.

我使用 Platform.runLater 命令以及服务类进行了尝试.结果总是一样.ProgressIndicator 显示出来,但没有动画.几秒钟后,所有面板立即出现.

I tried it with the Platform.runLater command as well as with a service class. The result was always the same. The ProgressIndicator are shown, but not animated. After seconds there are all panels at once.

有没有可能,指标一直是动画的,我可以一个接一个地交换它们?

Is there a possibility, that the Indicators are animated the whole time and that I can exchange them one after another?

推荐答案

JavaFX 具有用于 UI 事件的事件调度线程.所有与 UI 相关的工作都应该在这个线程上进行.并且不应在此处进行非 UI 计算以避免 UI 延迟.

JavaFX has Event Dispatch Thread which it uses for UI events. All work with UI should happen on this thread. And non-UI calculations shouldn't happen there to avoid lags in UI.

查看下一个代码:

public class Indicators extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        Pane root = new HBox();
        stage.setScene(new Scene(root, 300, 100));

        for (int i = 0; i < 10; i++) {
            final ProgressIndicator pi = new ProgressIndicator(0);
            root.getChildren().add(pi);

            // separate non-FX thread
            new Thread() {

                // runnable for that thread
                public void run() {
                    for (int i = 0; i < 20; i++) {
                        try {
                            // imitating work
                            Thread.sleep(new Random().nextInt(1000));
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                        final double progress = i*0.05;
                        // update ProgressIndicator on FX thread
                        Platform.runLater(new Runnable() {

                            public void run() {
                                pi.setProgress(progress);
                            }
                        });
                    }
                }
            }.start();
        }

        stage.show();

    }
}

这篇关于在 JavaFX 中在后台执行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆