I am implementing a custom TableCellFactory for asynchronously loading data from a database. The db request should not block the user interface thread.
public abstract class AsynchronousTableCellFactory<E, T> implements Callback<TableColumn<E, T>, TableCell<E, T>> {
private static final Executor exe1 = Executors.newFixedThreadPool(2);
private static final Executor exe2 = Executors.newFixedThreadPool(2);
@Override
public TableCell<E, T> call(final TableColumn<E, T> param) {
final TableCell<E, T> cell = new TableCell<E, T>() {
@Override
public void updateItem(final T item, final boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
} else {
setText("Thinking..");
exe1.execute(() -> {
if (getTableRow() != null) {
final Service<T> service = new Service<T>() {
@Override
protected Task<T> createTask() {
return getTask((E) getTableRow().getItem());
}
};
service.setExecutor(exe2);
service.setOnSucceeded(e -> {
if (e.getSource().getValue() == null) {
setText("n/a");
} else {
setText(e.getSource().getValue().toString());
}
});
service.setOnFailed(e -> {
final Throwable t = e.getSource().getException();
setText(t.getLocalizedMessage());
});
service.start();
}
});
}
}
};
return cell;
}
protected abstract Task<T> getTask(E rowDataItem);
}
It works most of the time, but not always. One strange thing is that T itemalways null.
In what cases can I expect what T itemwill happen null?
Corresponding table code:
public class OriginsTableViewController implements Initializable {
@FXML
private TableView<LazyLoadingOriginWrapper> table;
@FXML
private TableColumn<LazyLoadingOriginWrapper, String> cSampleName;
@Override
public void initialize(final URL location, final ResourceBundle resources) {
cSampleName.setCellFactory(new AsynchronousOriginTableCellFactory<>(e -> e.getSampleName()));
}
EDIT: Find a better approach here .
source
share