2

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.

kerner1000
  • 3,382
  • 1
  • 37
  • 57
  • 1
    Perhaps this [similar question](https://stackoverflow.com/questions/46474385/how-to-find-the-indices-of-the-visible-rows-in-a-tableview-in-javafx-9) will lead you in the right direction. – Zephyr Jan 01 '19 at 17:01

0 Answers0