我有15个项目的数据库,我在tableview中加载并在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() );
}
}
}
答案 0 :(得分:0)
您需要在分页上设置页数,以限制可用的页数。
将rowsPerPage
移动到字段(而不是局部变量),然后在加载数据后执行
public void initialize() {
// ...
buildData();
int pageCount = data.size() / rowsPerPage ;
if (pageCount * rowsPerPage < data.size()) {
pageCount = pageCount + 1 ;
}
page.setPageCount(pageCount);
}