当我使用 TableView<T>
时在JavaFX中,我经常称其为setAll()
给它一个新的List<T>
。但是,如果行数有点大,滚动条会随着项目的删除和添加而变得疯狂。
如何阻止这种行为?有没有办法在填充新的 List<T>
时“关闭”视觉更新?如果它的行为像这样,可能会让用户感觉不优雅并且烦人。
TableView<MyType> tableView = ...;
tableView.getItems().setAll(someList); //goes crazy for a second
更新 我被要求提供 SSCCE,我想出了这个。它没有像我的产品应用程序那样严重地反射(reflect)问题。但是,如果您将滚动条移动到中心,然后单击“重建”按钮,它就会跳来跳去。有没有办法可以在刷新期间保持滚动条固定?我想如果我能做到这一点,它将解决我更大的问题。
public final class TableViewJumpTest extends Application {
private Random rand = new Random();
private final Supplier<List<Integer>> listSupplier = () -> IntStream.range(0,rand.nextInt(100000))
.mapToObj(i -> rand.nextInt(10000)).collect(Collectors.toList());
@Override
public void start(Stage stage) throws Exception {
TableView<Integer> tableView = new TableView<>();
TableColumn<Integer,Number> col = new TableColumn<>("VALUE");
col.setCellValueFactory(cb -> new ReadOnlyIntegerWrapper(cb.getValue()));
tableView.getColumns().add(col);
tableView.getItems().setAll(listSupplier.get());
VBox vBox = new VBox();
vBox.getChildren().add(tableView);
Button bttn = new Button("REBUILD");
bttn.setOnAction(e -> tableView.getItems().setAll(listSupplier.get()));
vBox.getChildren().add(bttn);
stage.setScene(new Scene(vBox));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
最佳答案
我尝试过使用 setAll() 方法,实际上,当使用非常大的集合时,它开始表现得有点奇怪。我建议用以下内容替换 getItems().setAll() 。
tableView.setItems(FXCollections.observableArrayList(yourList));
setAll() 方法将迭代两个集合,我认为这会导致滚动条跳转,而 setItems() 只是抛出旧集合并将其替换为新集合。当使用非常大的数据集时,随着集合被一一添加到可观察集合中,滚动条仍然会收缩,但不像 setAll() 那样收缩。
如果您想保持排序,您可能需要在执行 setItems 之前获取 sortColumn 和 sortType,因为在添加新集合时这将被删除。
关于JavaFX 8-停止 TableView 在 setAll() 调用上跳转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32512654/