使用页面工厂处理分页

Handle pagination with page factory

我有一个 table 视图,其中包含一个带有 2 个子项的锚定窗格面板、一个 table 视图和一个分页。分页没有直接链接到 table 视图(就像你放置一个带有更新标签的按钮一样)。

我发现的唯一示例是分页本身通过其 setPageFactory 方法处理 UI 更新。

我知道我不应该这样设计,遗憾的是我现在没有时间去改变它。所以这是我目前的解决方案:

paginationTab1.setPageFactory(e -> {
    updateTableViewWithOffset(e);
    //hack, as the pagination is not directly linked with the tableView
    //just return an empty component that is not managed by the parent component
    Label l = new Label();
    l.setManaged(false);
    return l;
});

这是一个 acceptable 解决方法吗(return null 在 UI 之后更新不好...)?或者有没有办法获得与 setPageFactory 方法提供的相同的侦听器行为(即在分页的箭头或分页的数字上单击时获取页面偏移量)?

您可以观察 PaginationcurrentPageIndexProperty():

paginationTab1.currentPageIndexProperty().addListener((obs, oldIndex, newIndex) -> 
    updateTableViewWithOffset(newIndex.intValue()));

这是一个 SSCCE:

import java.util.stream.Collectors;
import java.util.stream.IntStream;

import javafx.application.Application;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.scene.Scene;
import javafx.scene.control.Pagination;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class IndependentPaginationTest extends Application {

    private static final int NUM_PAGES = 20 ;
    private static final int ITEMS_PER_PAGE = 20 ;

    @Override
    public void start(Stage primaryStage) {
        TableView<String> table = new TableView<>();
        TableColumn<String, String> col = new TableColumn<>("Item");
        table.getColumns().add(col);

        col.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue()));
        updateTable(table, 0);

        Pagination pagination = new Pagination();
        pagination.setPageCount(NUM_PAGES);

        pagination.currentPageIndexProperty().addListener((obs, oldIndex, newIndex) -> 
                updateTable(table, newIndex.intValue()));

        BorderPane root = new BorderPane(table, null, null, pagination, null);
        primaryStage.setScene(new Scene(root, 800, 600));
        primaryStage.show();
    }

    private void updateTable(TableView<String> table, Integer index) {
        int start = index * ITEMS_PER_PAGE + 1;
        int end = start + ITEMS_PER_PAGE ;
        table.getItems().setAll(
                IntStream.range(start, end)
                .mapToObj(Integer::toString)
                .map("Item "::concat)
                .collect(Collectors.toList()));
    }

    public static void main(String[] args) {
        launch(args);
    }
}