Pagination
Pagination in JavaFX is a control that lets you split content across multiple pages, with built-in navigation (like “Next” and “Previous” buttons). It’s useful when you have a large list, table, or images that should be shown page by page instead of all at once.
Here’s a full example to understand it.
Example: Display a List of Numbers in Pages
We’ll show 10 numbers per page using Pagination.
Controller (HelloController.java)
package org.example.demo;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.Pagination;
import javafx.scene.layout.VBox;
public class HelloController {
@FXML
private Pagination pagination;
private final int itemsPerPage = 10;
private final int totalItems = 95; // Example: 95 items
private final int totalPages = (int) Math.ceil((double) totalItems / itemsPerPage);
@FXML
public void initialize() {
pagination.setPageCount(totalPages);
pagination.setPageFactory(this::createPage);
}
private VBox createPage(int pageIndex) {
VBox box = new VBox(5);
int start = pageIndex * itemsPerPage;
int end = Math.min(start + itemsPerPage, totalItems);
for (int i = start + 1; i <= end; i++) {
box.getChildren().add(new Label("Item " + i));
}
return box;
}
}
FXML (hello-view.fxml)
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Pagination?>
<?import javafx.scene.layout.VBox?>
<VBox spacing="20" alignment="CENTER"
xmlns="http://javafx.com/javafx/17"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="org.example.demo.HelloController">
<Pagination fx:id="pagination"/>
</VBox>
How It Works
pagination.setPageCount(totalPages)→ sets how many pages exist.pagination.setPageFactory(this::createPage)→ tells JavaFX how to create each page.createPage(int pageIndex)→ builds aVBoxwith the items for that page.
JavaFX automatically adds the page navigation buttons at the bottom:
< Previous 1 2 3 ... Next >
Dynamic Use Cases
- Image galleries
- Search results
- Large tables/lists
- Forms split into multiple steps