How to implement paging for a TableView in JavaFX?

2019-07-12 02:56发布

问题:

This question already has an answer here:

  • JavaFX TableView Paginator 3 answers

I have JavaFx TableView, and want to implement tableView paging display. How to javaFx tableView Implement paging display?

回答1:

You have to use the Pagination control and implement a page factory. The factory is called for every page that should be displayed and you can use its parameter, the pageIndex, to provide a sublist of items to the TableView:

TableView table = ...

private Node createPage(int pageIndex) {

    int fromIndex = pageIndex * rowsPerPage;
    int toIndex = Math.min(fromIndex + rowsPerPage, data.size());
    table.setItems(FXCollections.observableArrayList(data.subList(fromIndex, toIndex)));

    return new BorderPane(table);
}


@Override
public void start(final Stage stage) throws Exception {

    Pagination pagination = new Pagination((data.size() / rowsPerPage + 1), 0);
    pagination.setPageFactory(this::createPage);
    ...
}

A complete runnable example can be found here: https://gist.github.com/timbuethe/7becdc4556225e7c5b7b

PS: I followed jewelsea link to the Oracle JavaFX Forums, and the example is really bad. I wanted to provide an cleaned up example here.