【发布时间】:2015-01-30 02:06:46
【问题描述】:
我来自 Swing 背景并尝试学习 JavaFx。
这个ObservableList 正在填充字符串,并添加到ListView。
当我在同一个线程中将一个项目添加到可观察列表中时,一切正常。
但是,当我尝试从 不同的线程 将项目添加到可观察列表时,这些项目被添加了两次。对于我的生活,我无法弄清楚为什么。调试语句显示线程实际上只执行一次。
这是一个完整的示例:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.util.Callback;
public class FeedPanelViewer extends Application {
public static void main(String[] args) {
launch(args);
}
String greeting = "<html><body><p><strong>hi ya'll</strong></p></body></html>";
@Override
public void start(Stage stage) {
ObservableList<String> names = FXCollections.observableArrayList("Matthew", "Hannah", "Stephan", "Denise");
ListView<String> listView = new ListView<String>(names);
stage.setScene(new Scene(listView));
stage.show();
listView.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
@Override
public ListCell<String> call(ListView<String> list) {
return new HtmlFormatCell();
}
});
// This thread is definitely only adding items once
new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
Platform.runLater(() -> {
System.out.println("Got here");
names.add(greeting);
names.add("andrew");
});
}).start();
}
public class HtmlFormatCell extends ListCell<String> {
public HtmlFormatCell() {
}
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
if (item.contains("<p>")) {
Platform.runLater(() -> {
WebView web = new WebView();
WebEngine engine = web.getEngine();
engine.loadContent(item);
web.setPrefHeight(50);
web.setPrefWidth(300);
web.autosize();
setText("");
setGraphic(web);
});
} else {
setText(item == null ? "" : "-" + item);
setTextFill(Color.BLUE);
if (isSelected()) {
setTextFill(Color.GREEN);
}
}
}
}
}
}
如果我注释掉new Thread(() -> { 和}).start(); 这两行,这就是我看到的:
随着Thread 包裹着两个列表元素的添加,我看到了这个,它渲染了两次单元格,即使线程只执行了一次:
谁能帮忙指出是怎么回事?
非常感谢。
【问题讨论】:
标签: java multithreading javafx-8