[英]Generate value in seperate thread for TableColumn in JavaFX
目前,在為JavaFX應用程序開發時,在填充表方面遇到了一個小問題。 在我當前的設置中,我有以下內容:
infoColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures, ObservableValue>() {
@Override
public ObservableValue call(TableColumn.CellDataFeatures cellDataFeatures) {
DataMessage dataMessage = (DataMessage) cellDataFeatures.getValue();
SimpleStringProperty infoProperty = new SimpleStringProperty("Loading...");
if (dataMessage != null) {
if (isMessageNotification(dataMessage)) {
Notification notification = getNotificationFromMessage(dataMessage);
infoProperty.set(LanguageUtils.getNotificationInfo(dataMessage, notification));
} else if (isMessageRequest(dataMessage)) {
Request request = getRequestFromMessage(dataMessage);
infoProperty.set(LanguageUtils.getRequestInfo(dataMessage, request));
}
}
return infoProperty;
}
});
對LanguageRegistry(我自己的類)的調用使用一些資源來加載與指定對象相關的不同對象。 這導致我的應用程序凍結了幾秒鍾以填充列表,因為這些是通知和請求,它們將實時出現,因此需要在后台加載,因此不會打擾用戶。
我最初嘗試執行的操作是在另一個線程的“ if(dataMessage!= null)”中運行代碼,並在代碼執行完成時設置infoProperty字符串的值。 不幸的是,這似乎沒有用,桌子上只是無限期地顯示“正在加載...”。
因此,基本上我的問題是標題,我需要我的cellValueFactory代碼在單獨的線程中運行,以免凍結應用程序。 如果問題中有不清楚的地方,請告訴我,我將對其進行更改。
您不能使用單元格值工廠來延遲加載數據。 您可以在模型類( DataMessage
)本身中執行此操作,如下例所示:
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ObjectPropertyBase;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class BackgroundLoadingTableCell extends Application {
private static final Random rng = new Random();
private static final Executor exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), r -> {
Thread t = new Thread(r);
t.setDaemon(true);
return t ;
});
@Override
public void start(Stage primaryStage) {
TableView<Item> table = new TableView<>();
table.getColumns().add(column("Item", Item::nameProperty));
table.getColumns().add(column("Value", Item::valueProperty));
table.getColumns().add(column("Data", Item::dataProperty));
IntStream.rangeClosed(1, 100).mapToObj(i -> new Item("Item "+i, rng.nextInt(100))).forEach(table.getItems()::add);
primaryStage.setScene(new Scene(new BorderPane(table), 600, 600));
primaryStage.show();
}
private <S,T> TableColumn<S,T> column(String text, Function<S, ObservableValue<T>> property) {
TableColumn<S,T> col = new TableColumn<>(text);
col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
return col ;
}
public static class Item {
private final StringProperty name = new SimpleStringProperty();
private final IntegerProperty value = new SimpleIntegerProperty();
private final ObjectProperty<String> data = new ObjectPropertyBase<String>() {
@Override
public Object getBean() {
return Item.this;
}
@Override
public String getName() {
return "data";
}
@Override
public String get() {
String value = super.get();
if (value == null) {
Task<String> loadDataTask = new Task<String>() {
@Override
public String call() {
return getData(Item.this.getValue());
}
};
loadDataTask.setOnSucceeded(e -> set(loadDataTask.getValue()));
exec.execute(loadDataTask);
return "Loading..." ;
}
return value ;
}
};
public Item(String name, int value) {
setName(name);
setValue(value);
}
private String getData(int value) {
// simulate long running process:
try {
Thread.sleep(250 + rng.nextInt(500));
} catch (InterruptedException exc) {
Thread.currentThread().interrupt();
}
return "Data for "+value ;
}
public final StringProperty nameProperty() {
return this.name;
}
public final java.lang.String getName() {
return this.nameProperty().get();
}
public final void setName(final java.lang.String name) {
this.nameProperty().set(name);
}
public final IntegerProperty valueProperty() {
return this.value;
}
public final int getValue() {
return this.valueProperty().get();
}
public final void setValue(final int value) {
this.valueProperty().set(value);
}
public final ObjectProperty<String> dataProperty() {
return this.data;
}
public final java.lang.String getData() {
return this.dataProperty().get();
}
public final void setData(final java.lang.String data) {
this.dataProperty().set(data);
}
}
public static void main(String[] args) {
launch(args);
}
}
或者,您可以將DataMessage
視為此單元格的值,然后延遲更新cellFactory
的單元格:
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class BackgroundLoadingTableCell extends Application {
private static final Random rng = new Random();
private static final Executor exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), r -> {
Thread t = new Thread(r);
t.setDaemon(true);
return t ;
});
@Override
public void start(Stage primaryStage) {
TableView<Item> table = new TableView<>();
table.getColumns().add(column("Item", Item::nameProperty));
table.getColumns().add(column("Value", Item::valueProperty));
TableColumn<Item, Item> dataColumn = column("Data", item -> new ReadOnlyObjectWrapper<Item>(item));
dataColumn.setCellFactory(col -> new TableCell<Item, Item>() {
private Task<String> dataLoadTask ;
@Override
public void updateItem(Item item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText("");
} else {
setText("Loading...");
if (dataLoadTask != null) {
dataLoadTask.cancel();
}
dataLoadTask = new Task<String>() {
@Override
public String call() {
return getData(item.getValue());
};
};
dataLoadTask.setOnSucceeded(e -> setText(dataLoadTask.getValue()));
exec.execute(dataLoadTask);
}
}
});
table.getColumns().add(dataColumn);
IntStream.rangeClosed(1, 100).mapToObj(i -> new Item("Item "+i, rng.nextInt(100))).forEach(table.getItems()::add);
primaryStage.setScene(new Scene(new BorderPane(table), 600, 600));
primaryStage.show();
}
private String getData(int value) {
// simulate long running process:
try {
Thread.sleep(250 + rng.nextInt(500));
} catch (InterruptedException exc) {
Thread.currentThread().interrupt();
}
return "Data for "+value ;
}
private <S,T> TableColumn<S,T> column(String text, Function<S, ObservableValue<T>> property) {
TableColumn<S,T> col = new TableColumn<>(text);
col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
return col ;
}
public static class Item {
private final StringProperty name = new SimpleStringProperty();
private final IntegerProperty value = new SimpleIntegerProperty();
public Item(String name, int value) {
setName(name);
setValue(value);
}
public final StringProperty nameProperty() {
return this.name;
}
public final java.lang.String getName() {
return this.nameProperty().get();
}
public final void setName(final java.lang.String name) {
this.nameProperty().set(name);
}
public final IntegerProperty valueProperty() {
return this.value;
}
public final int getValue() {
return this.valueProperty().get();
}
public final void setValue(final int value) {
this.valueProperty().set(value);
}
}
public static void main(String[] args) {
launch(args);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.