分页使我的应用程序崩溃

pagination crashes my appl

我有这个数据库,其中有 15 个项目,我将它们加载到一个表视图中,并将行数设置为 10。它加载前 10 个(在第 1 页),并使用分页加载最后一个5(第 2 页)。但是,当我继续分页时,它崩溃了。显然没有更多的行可以显示项目但是我该如何解决这个问题?

public class ProductListController implements Initializable {

@FXML private Pagination page;


    @Override
    public void initialize(URL url, ResourceBundle rb) {

        assert tableview !=null : " "; 

         ProductName.setCellValueFactory(cellData -> cellData.getValue().productNameProperty());
         ProductPrice.setCellValueFactory(cellData -> cellData.getValue().productPriceProperty());
         Stock.setCellValueFactory(cellData -> cellData.getValue().productStockProperty());
         Supplier.setCellValueFactory(cellData -> cellData.getValue().productSupplierProperty());
         Contact.setCellValueFactory(cellData -> cellData.getValue().productContactProperty());
         buildData();        
    }

        private ObservableList<MyTable> data;

    private Node createPage(int pageIndex) {
    int rowsPerPage = 10;
    int fromIndex = pageIndex * rowsPerPage;
    int toIndex = Math.min(fromIndex + rowsPerPage, data.size());
    tableview.setItems(FXCollections.observableArrayList(data.subList(fromIndex, toIndex)));

    return (tableview);
}

   public void buildData(){
    data = FXCollections.observableArrayList();

          try{
        MyConnection mc = new MyConnection ();
        ResultSet rs; 
        rs = mc.getConnection();


    while (rs.next()) {
     MyTable mod = new MyTable();


     mod.productName.set(rs.getString("NAME"));
     mod.productPrice.set(rs.getString("SELL_PRICE"));
     mod.productStock.set(rs.getInt("STOCK"));
     mod.productSupplier.set(rs.getString("SUPPLIER"));
     mod.productContact.set(rs.getString("CONTACT"));

     data.add(mod);

     page.setPageFactory(this::createPage);
         }

      }

    catch ( SQLException | IOException err) {
    System.out.println(err.getMessage() ); 
    }


    }
}     

您需要在分页上设置页数,以限制可用页数。

rowsPerPage 移动到一个字段(而不是局部变量),然后在加载数据后执行

public void initialize() {
    // ...
    buildData();
    int pageCount = data.size() / rowsPerPage ;
    if (pageCount * rowsPerPage < data.size()) {
        pageCount = pageCount + 1 ;
    }
    page.setPageCount(pageCount);
}