How to Create an Advanced Paginated Table in Java Swing Using Netbeans
In this Java Tutorial we will see How To Create a complete paginated table with custom styling, navigation controls, and Jump-to-page functionality In Java Using Netbeans.
Project Overview:
Our paginated table will include:
- 1000 sample records with ID, Name, Email, and Status columns
- Configurable page sizes (5, 10, 15, 20 rows)
- Navigation controls (First, Previous, Next, Last)
- Page number buttons with ellipsis for large datasets
- Jump-to-page functionality
What We Are Gonna Use In This Project:
- Java Programming Language.- NetBeans Editor.
Project Source Code:
public class PaginatedTable extends JFrame {
private JTable table;
private DefaultTableModel model;
private JPanel paginationPanel;
private int currentPage = 1;
private int recordPerPage = 5;
private List<Object[]> allData;
private int totalPages;
private JComboBox<String> pageSizeCombo;
private JTextField pageJump;
private final Color primaryColor = new Color(79, 70, 229);
private final Color borderColor = new Color(229, 231, 235);
private final Color backgroundColor = new Color(249, 250, 251);
private final Color textColor = new Color(17, 24, 39);
public PaginatedTable(){
setTitle("Paginated Table");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initializeComponents();
setupLayout();
loadSampleData();
updateTable();
setSize(1000, 600);
setLocationRelativeTo(null);
setVisible(true);
}
// Initialize all UI components
private void initializeComponents(){
String[] columns = {"ID", "Name", "Email", "Status"};
model = new DefaultTableModel(columns, 0);
table = new JTable(model);
customizeTable(table);
// Create custom cell renderer for modern look
DefaultTableCellRenderer cellRender = new DefaultTableCellRenderer(){
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column){
Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setBorder(new EmptyBorder(0, 20, 0, 20));
if(!isSelected){ setBackground(row % 2 == 0 ? Color.WHITE : backgroundColor); }
return comp;
}
};
cellRender.setHorizontalAlignment(JLabel.LEFT);
for(int i = 0; i < table.getColumnCount(); i++){
table.getColumnModel().getColumn(i).setCellRenderer(cellRender);
}
paginationPanel = new JPanel();
paginationPanel.setBackground(Color.WHITE);
pageSizeCombo = new JComboBox<>(new String[]{"5 rows", "10 rows", "15 rows", "20 rows"});
pageSizeCombo.setFont(new Font("Arial", Font.PLAIN, 17));
// Add change listener for page size
pageSizeCombo.addActionListener(e -> {
String selected = (String) pageSizeCombo.getSelectedItem();
recordPerPage = Integer.parseInt(selected.split(" ")[0]); // Update records per page
currentPage = 1; // Reset to first page
totalPages = (int) Math.ceil((double) allData.size() / recordPerPage); // Recalculate total pages
updateTable(); // Refresh table
});
pageJump = new JTextField(3);
pageJump.setFont(new Font("Arial", Font.PLAIN, 14));
// Add action listener for page jumping
pageJump.addActionListener(e -> {
try{
int page = Integer.parseInt(pageJump.getText()); // Validate page number
if(page >= 1 && page <= totalPages){
currentPage = page; // Update current page
updateTable(); // Refresh table
}
}
catch(NumberFormatException ex){ /* Ignore invalid input*/ }
pageJump.setText(""); // Clear input field
});
}
// Load sample data for demonstration
private void loadSampleData(){
allData = new ArrayList<>(); // Initialize data list
String[] status = { "Active", "Pending", "Completed", "Inactive"}; // Define possible statuses
Random random = new Random();
// Generate 1000 sample records
for(int i = 1; i <= 1000; i++){
allData.add(new Object[]{
String.format("#%03d", i), // Format ID with leading zeros
"User" + i, // Generate user name
"user" + i + "@example.com", // Generate email
status[random.nextInt(status.length)] // Random status
});
}
// Calculate total pages
totalPages = (int)Math.ceil((double)allData.size() / recordPerPage);
}
// Setup the main layout
private void setupLayout(){
setLayout(new BorderLayout()); // Use border layout for main frame
// Create main panel with shadow effect
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setBackground(Color.darkGray); // Set panel background
mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); // Add padding
// Create table container
JPanel tableContainer = new JPanel(new BorderLayout());
tableContainer.setBackground(Color.WHITE); // Set container background
tableContainer.setBorder(BorderFactory.createLineBorder(borderColor, 1)); // Add border
// Create scroll pane for table
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(BorderFactory.createEmptyBorder()); // Remove scroll pane border
scrollPane.getViewport().setBackground(Color.WHITE); // Set viewport background
// Assemble components
tableContainer.add(scrollPane); // Add table to container
mainPanel.add(tableContainer, BorderLayout.CENTER); // Add container to main panel
mainPanel.add(paginationPanel, BorderLayout.SOUTH); // Add pagination to main panel
add(mainPanel); // Add main panel to frame
}
// Update table data based on current page
private void updateTable(){
model.setRowCount(0); // Clear current table data
int start = (currentPage - 1) * recordPerPage; // Calculate start index
int end = Math.min(start + recordPerPage, allData.size()); // Calculate end index
// Add rows for current page
for(int i = start; i < end; i++){
model.addRow(allData.get(i));
}
updatePagination(); // Update pagination controls
}
// Update pagination controls
private void updatePagination(){
paginationPanel.removeAll(); // Clear existing controls
paginationPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 15)); // Set layout
// Create left section with page size selector and total records
JPanel leftSection = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0));
leftSection.setBackground(Color.WHITE);
leftSection.add(pageSizeCombo);
// Add total records label
JLabel totalRecords = new JLabel(String.format("Total: %d records", allData.size()));
totalRecords.setFont(new Font("Arial", Font.PLAIN, 14));
leftSection.add(totalRecords);
// Create center section for navigation
JPanel centerSection = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0));
centerSection.setBackground(Color.WHITE);
// Add navigation buttons
// First page button
addPaginationButton(centerSection, "⟪", currentPage > 1, () -> {
currentPage = 1;
updateTable();
});
// Previous page button
addPaginationButton(centerSection, "←", currentPage > 1, () -> {
currentPage--;
updateTable();
});
// Add page number buttons
int start = Math.max(1, currentPage - 2); // Calculate start page
int end = Math.min(totalPages, start + 4); // Calculate start page
// Add ellipsis if needed
if(start > 1){ centerSection.add((new JLabel("..."))); }
// Add page number buttons
for(int i = start; i <= end; i++){
final int page = i;
addPageButton(centerSection, String.valueOf(i), i == currentPage, () -> {
currentPage = page;
updateTable();
});
}
// Add ellipsis if needed
if(end < totalPages){ centerSection.add((new JLabel("..."))); }
// Add next and last page buttons
addPaginationButton(centerSection, "→", currentPage < totalPages, () -> { // Next page button
currentPage++;
updateTable();
});
addPaginationButton(centerSection, "⟫", currentPage < totalPages, () -> { // Last page button
currentPage = totalPages;
updateTable();
});
// Create right section with page jump
JPanel rightSection = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 0));
rightSection.setBackground(Color.WHITE);
// Add page jump label and field
JLabel jumpLabel = new JLabel("Go to page");
jumpLabel.setFont(new Font("Arial", Font.PLAIN, 14));
rightSection.add(jumpLabel);
rightSection.add(pageJump);
// Add all sections to pagination panel
paginationPanel.add(leftSection);
paginationPanel.add(centerSection);
paginationPanel.add(rightSection);
// Refresh panel
paginationPanel.revalidate();
paginationPanel.repaint();
}
// Add navigation button to pagination panel
private void addPaginationButton(JPanel panel, String text, boolean enabled, Runnable action){
JButton button = createButton(text, enabled, false); // Create styled button
button.addActionListener(e -> action.run()); // Add click handler
panel.add(button); // Add to panel
}
// Add page number button to pagination panel
private void addPageButton(JPanel panel, String text, boolean isActive, Runnable action){
JButton button = createButton(text, true, isActive); // Create styled button
button.addActionListener(e -> action.run()); // Add click handler
panel.add(button); // Add to panel
}
// Create styled button with modern look
private JButton createButton(String text, boolean enabled, boolean isActive){
// Create custom button with modern painting
JButton button = new JButton(text) {
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Set button background color
if (isActive) { g2d.setColor(primaryColor); } // Active state
else { g2d.setColor(Color.lightGray); } // Normal state
// Draw button background
g2d.fill(new RoundRectangle2D.Double(0, 0, getWidth(), getHeight(), 10, 10));
// Draw button border
if (!isActive) {
g2d.setColor(borderColor);
g2d.draw(new RoundRectangle2D.Double(0, 0, getWidth() - 1, getHeight() - 1, 10, 10));
}
// Set text color
g2d.setColor(isActive ? Color.WHITE : enabled ? textColor : Color.GRAY);
// Center and draw text
FontMetrics fm = g2d.getFontMetrics();
int x = (getWidth() - fm.stringWidth(getText())) / 2;
int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
g2d.drawString(getText(), x, y);
g2d.dispose(); // Clean up graphics context
}
};
// Configure button styling
button.setFont(new Font("Inter", Font.PLAIN, 14)); // Set button font
button.setPreferredSize(new Dimension(40, 40)); // Set button size
button.setFocusPainted(false); // Remove focus border
button.setBorderPainted(false); // Remove default border
button.setContentAreaFilled(false); // Remove default background
button.setEnabled(enabled); // Set button state
button.setCursor(enabled ? new Cursor(Cursor.HAND_CURSOR) : // Set appropriate cursor
new Cursor(Cursor.DEFAULT_CURSOR));
return button; // Return the styled button
}
private void customizeTable(JTable table) {
// Colors
Color HEADER_BACKGROUND = new Color(52, 73, 94);
Color HEADER_FOREGROUND = Color.WHITE;
Color ROW_ALTERNATE = new Color(245, 245, 245);
Color SELECTION_COLOR = new Color(52, 152, 219);
// Customize header
JTableHeader header = table.getTableHeader();
header.setBackground(HEADER_BACKGROUND);
header.setForeground(HEADER_FOREGROUND);
header.setFont(header.getFont().deriveFont(Font.BOLD, 14f));
header.setBorder(BorderFactory.createEmptyBorder());
// Set custom renderer for header
TableCellRenderer headerRenderer = new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
JLabel label = (JLabel) super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
label.setBackground(HEADER_BACKGROUND);
label.setForeground(HEADER_FOREGROUND);
label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return label;
}
};
for (int i = 0; i < table.getColumnCount(); i++) {
table.getColumnModel().getColumn(i).setHeaderRenderer(headerRenderer);
}
// Customize table appearance
table.setRowHeight(40);
table.setFont(new Font("Arial", Font.PLAIN, 13));
table.setSelectionBackground(SELECTION_COLOR);
table.setSelectionForeground(Color.WHITE);
table.setShowVerticalLines(false);
table.setShowHorizontalLines(true);
table.setGridColor(new Color(230, 230, 230));
table.setIntercellSpacing(new Dimension(0, 0));
// Custom renderer for alternating row colors
DefaultTableCellRenderer cellRenderer = new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
JLabel label = (JLabel) super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
if (!isSelected) {
label.setBackground(row % 2 == 0 ? Color.WHITE : ROW_ALTERNATE);
}
label.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
// Right-align numbers
if (value instanceof Number) {
label.setHorizontalAlignment(SwingConstants.RIGHT);
} else {
label.setHorizontalAlignment(SwingConstants.LEFT);
}
return label;
}
};
for (int i = 0; i < table.getColumnCount(); i++) {
table.getColumnModel().getColumn(i).setCellRenderer(cellRenderer);
}
// Enable sorting
table.setAutoCreateRowSorter(true);
}
public static void main(String[] args) {
// Set system look and feel for native appearance
/*
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace(); // Print any errors
}
*/
new PaginatedTable();
}
}
The Final Result:
More Java Projects:
Download Projects Source Code



