I would like to add items to a table dynamically. I do it like this:
public class TestApp extends Application {
public static void main(final String[] args) {
launch(args);
}
private final AtomicLong counter = new AtomicLong();
@Override
public void start(final Stage primaryStage) {
final VBox root = new VBox(5);
root.setPadding(new Insets(10));
root.setAlignment(Pos.CENTER);
final TableView<String> tableView = new TableView<>();
final TableColumn<String, String> column = new TableColumn<>("Text");
column.setCellValueFactory(f -> new SimpleStringProperty(f.getValue()));
tableView.getColumns().add(column);
// Add some sample items to our TableView
for (int i = 0; i < 100; i++) {
tableView.getItems().add("Item #" + counter.incrementAndGet());
}
final Button button = new Button("Add items");
final long oldElement = counter.get();
button.setOnAction(e -> {
// Add more elements
for (int i = 0; i < 10; i++) {
tableView.getItems().add("Item #" + counter.incrementAndGet());
}
tableView.scrollTo("Item #" + oldElement);
});
root.getChildren().add(button);
root.getChildren().add(tableView);
// Show the Stage
primaryStage.setWidth(300);
primaryStage.setHeight(300);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
(Example taken from here)
What I would like to change now, is, that when the table is already scrolled down completely, and I add more items, the table automatically scrolls down.
The 'scroll-state' seems to be maintained, which is why I still see the very bottom of the table (and the new elements).
How can I add items to the table but keeping the scroll at the current position / current row?
The 'scrollTo' works, but moves the last element from the bottom of the view to the top, which is also a litte irritating.