1
\$\begingroup\$

I am trying to create simple app, where I need a pagination for my JTable. I want have there buttons with number for all "pages" in my JTable. I have code here:

Class Customer:

package customereditor;

public class Customer {

    private int ID;
    private String name;
    private String surname;

    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

}

Class CustomerEditorDao

package customereditor;

import java.sql.*;
import java.util.*;
import java.util.logging.*;    

public class CustomerEditorDao {

    public List<Customer> getCustomersByPage(int page) {
        List<Customer> customers = new ArrayList();
        try {
            Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/CustomerEditorDb");
            Statement stmt = conn.createStatement();
            String subSql = "SELECT * FROM Customer OFFSET %d ROWS FETCH NEXT 5 ROWS ONLY";
            String sql = String.format(subSql, page);
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                Customer customer = new Customer();
                customer.setID(rs.getInt(1));
                customer.setName(rs.getString(2));
                customer.setSurname((rs.getString(3)));
                customers.add(customer);
            }

        } catch (SQLException ex) {
            Logger.getLogger(CustomerEditorDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return customers;
    }

    public int getRowCount() {
        int rows = 0;
        try {
            Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/CustomerEditorDb");
            Statement stmt = conn.createStatement();
            String sql = "SELECT COUNT(*) FROM Customer";
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                rows = rs.getInt(1);
            }

        } catch (SQLException ex) {
            Logger.getLogger(CustomerEditorDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return columns;
    }

}

Class CustomerEditorMain

package customereditor;

import javax.swing.*;

public class CustomerEditorMain {


        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("TableDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            CustomerView view = new CustomerView();
            frame.add(view);

            //Display the window.
            frame.pack();
            frame.setVisible(true);
        }

        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }

    }

Class CustomerTableModel

package customereditor;

import java.util.List;
import javax.swing.table.AbstractTableModel;

public class CustomerTableModel extends AbstractTableModel {

    private final String[] COLUMN_NAMES;
    List<Customer> customers; 

    public CustomerTableModel(List<Customer> customers) {
        this.COLUMN_NAMES = new String[]{"ID", "Name", "Surname"};
        this.customers = customers;
    }

    @Override
    public int getColumnCount() {

        return COLUMN_NAMES.length;
    }

    @Override
    public int getRowCount() {

        return customers.size();
    }

    @Override
    public String getColumnName(int col) {

        return COLUMN_NAMES[col];
    }

    @Override
    public Object getValueAt(int row, int col) {

        Customer customer = customers.get(row);

        switch (col) {
            case 0:
                return customer.getID();
            case 1:
                return customer.getName();
            case 2:
                return customer.getSurname();
        }

        return customer;
    }

}

and class CustomerEditorView

    package customereditor;

    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.*;

   public class CustomerView extends JPanel {

        private CustomerTableModel model;
        private JTable table;
        private CustomerEditorDao dao;
        JButton next;
        JButton previous;

        public CustomerView() {
            initComponents();
        }

        private void initComponents() {
            setLayout(new BorderLayout());
            dao = new CustomerEditorDao();
            model = new CustomerTableModel(dao.getCustomersByPage(0));
            table = new JTable(model);
            add(table.getTableHeader(), BorderLayout.PAGE_START);
            add(table, BorderLayout.CENTER);

            JPanel buttonsPanel = new JPanel();
            Map<Integer, JButton> buttons = new HashMap<Integer, JButton>();
            int pages;
            int rowCount = dao.getRowCount();
            if (rowCount % 5 == 0) {
                pages = rowCount / 5;
            } else {
                pages = rowCount / 5 + 1;
            }

            for (int i = 1; i <= pages; i++) {
                String buttonText = Integer.toString(i);
                JButton button = new JButton(buttonText);
                buttons.put(i, button);
                buttons.get(i).addActionListener(new ButtonActionListener(table, buttons.get(i)));
                buttonsPanel.add(buttons.get(i));
            }

            add(buttonsPanel, BorderLayout.PAGE_END);

        }

    }

    class ButtonActionListener implements ActionListener {

        JTable table;
        JButton button;

        public ButtonActionListener(JTable table, JButton button) {
            this.table = table;
            this.button = button;
        }

        @Override
        public void actionPerformed(ActionEvent ae) {
           CustomerEditorDao dao = new CustomerEditorDao();
           int number = Integer.parseInt(button.getText());       
           CustomerTableModel model = new CustomerTableModel(dao.getCustomersByPage((number * 5)-5));
           table.setModel(model);
        }


    }

In class CustomerEditorDao I have something like this:

String subSql = "SELECT * FROM Customer OFFSET %d ROWS FETCH NEXT 5 ROWS ONLY";

So I always offset XXX rows and I want 5 results per page, so I fetch next 5 rows. I am using Derby db.

My question is what is the best way to provide pagination for JTable? In actionlistener I use text of JButtons and I think that is not good idea.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.