2

有没有办法同步 JavaFX 平台线程和标准 Java 线程?目前,当触发时,JavaFX 线程会在标准 Java 线程完成将所有图像添加到可观察列表之前触发,因此 imageList 会更新为空白集合。

private final TilePane imageList;
final File[] files = new File(dir).listFiles();
final List<ImageView> views = FXCollections.observableArrayList();

new Thread() {
        @Override
        public void run() {
            for (final File file : files) {
                if (Utils.fileIsImage(file) && !file.isDirectory()) {
                    ImageView view = new ImageView(new Image("file:" + file, 72, 72, false, true));
                    views.add(view);
                }
            }
        }
    }.start();
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            imageList.getChildren().addAll(views);
        }
    });

我对 JavaFX 和并发性比较陌生,对线程锁没有任何经验,所以任何帮助都会很棒。谢谢!

4

1 回答 1

4
new Thread() {
    @Override
    public void run() {
        for (final File file : files) {
            if (Utils.fileIsImage(file) && !file.isDirectory()) {
                ImageView view = new ImageView(new Image("file:" + file, 72, 72, false, true));
                views.add(view);
            }
        }

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                imageList.getChildren().addAll(views);
            }
        });
    }
}.start();

考虑一个一个添加视图,只要它们被加载:

if (Utils.fileIsImage(file) && !file.isDirectory()) {
    ImageView view = new ImageView(new Image("file:" + file, 72, 72, false, true));
    views.add(view);

    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            imageList.getChildren().add(view);
        }
    });
}
于 2012-11-07T06:59:42.290 回答