Pagination Tutorial With Live Data in Java Swing

Pagination Example in Java Swing with Live JSON Data (2026)

Pagination Example in Java Swing with Live JSON Data

In this tutorial, you will learn how to build a pagination example in Java Swing that fetches live JSON data from a REST API, stores it in MySQL, and displays it page by page in a JTable. Each page shows ten rows, and the navigation buttons at the bottom let you jump between pages.

You will use JDBC for the database connection, Gson for JSON parsing, and SQL LIMIT with an offset for paginated queries.

Output Screen

Below is the final pagination window with the data grid and page navigation buttons:

Java Swing pagination example — JTable with page navigation buttons

SQL Query

Create the posts table in MySQL before running the Java code:

mysql> create table posts (
    userid int,
    id int primary key,
    title varchar(80),
    body varchar(250)
);

Post.java (Model)

package com.deepsingh44.blogspot.model;

public class Post {
    private int userId;
    private int id;
    private String title;
    private String body;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }
}

Dao.java (Connection Helper)

This class provides a single reusable JDBC connection method:

package com.deepsingh44.blogspot.dao;

import java.sql.Connection;
import java.sql.DriverManager;

public class Dao {
    public static Connection con;

    public static Connection getMyConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/mydatabase",
                "username",
                "password"
            );
        } catch (Exception e) {
            System.out.println(e);
        }
        return con;
    }
}

PaginationDemo.java (Main Class)

This is the main Swing class. It checks whether the database has data, fetches live JSON from an API if empty, builds the pagination buttons dynamically, and updates the JTable when a page button is clicked.

package com.deepsingh44.blogspot.ui;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.BevelBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;

import org.json.JSONArray;

import com.deepsingh44.blogspot.dao.Dao;
import com.deepsingh44.blogspot.model.Post;
import com.google.gson.Gson;

import javax.swing.JTextField;
import javax.swing.JTable;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.swing.border.LineBorder;

public class PaginationDemo extends JFrame implements ActionListener {

    private JPanel contentPane;
    private JTable table;
    int page = 1;
    int perpage = 10;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    PaginationDemo frame = new PaginationDemo();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    List<JButton> buttons;

    public PaginationDemo() {
        setTitle("Pagination Tutorial With Live Data");

        int rowcount = getAllRowCount();
        if (rowcount == 0) {
            storeLiveData();
        }

        int numbuttons = rowcount / perpage;

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 586, 464);

        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        String[] cols = { "Id", "Title", "Body" };
        DefaultTableModel dt = new DefaultTableModel(cols, 0);

        table = new JTable(dt);
        table.setRowHeight(24);

        JScrollPane jp = new JScrollPane(table);
        jp.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
        jp.setBounds(22, 38, 518, 262);
        contentPane.add(jp);

        JPanel panel = new JPanel();
        panel.setBorder(new LineBorder(new Color(0, 0, 0)));
        panel.setBounds(22, 340, 518, 34);
        contentPane.add(panel);

        buttons = new ArrayList<>();
        for (int i = 1; i <= numbuttons; i++) {
            JButton b1 = new JButton(String.valueOf(i));
            b1.setActionCommand(String.valueOf(i));
            b1.setBackground(Color.RED);
            b1.setForeground(Color.WHITE);
            b1.addActionListener(this);
            panel.add(b1);
            buttons.add(b1);

            if (b1.getActionCommand().equals("1")) {
                call("1");
                b1.setBackground(Color.GREEN);
            }
        }
    }

    public int getAllRowCount() {
        int rowcount = 0;
        try (Connection con = Dao.getMyConnection();) {
            PreparedStatement ps = con.prepareStatement("select count(*) from posts");
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                rowcount = rs.getInt(1);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return rowcount;
    }

    private List<Post> getData(int start, int perpage) {
        List<Post> posts = new ArrayList<>();
        try (Connection con = Dao.getMyConnection();) {
            PreparedStatement ps = con.prepareStatement("select * from posts limit ?,?");
            ps.setInt(1, start);
            ps.setInt(2, perpage);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Post post = new Post();
                post.setUserId(rs.getInt(1));
                post.setId(rs.getInt(2));
                post.setTitle(rs.getString(3).toUpperCase(Locale.getDefault()));
                post.setBody(rs.getString(4).toUpperCase(Locale.getDefault()));
                posts.add(post);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return posts;
    }

    private void storeLiveData() {
        try {
            URL url = new URL("https://jsonplaceholder.typicode.com/posts");
            HttpURLConnection hr = (HttpURLConnection) url.openConnection();
            InputStream im = hr.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(im));
            StringBuffer sb = new StringBuffer();

            String line = br.readLine();
            while (line != null) {
                sb.append(line).append("\n");
                line = br.readLine();
            }

            JSONArray jsonArray = new JSONArray(sb.toString());
            Gson gson = new Gson();

            try (Connection con = Dao.getMyConnection();) {
                PreparedStatement ps = con.prepareStatement("insert into posts values(?,?,?,?)");
                for (int i = 0; i < jsonArray.length(); i++) {
                    Post post = gson.fromJson(jsonArray.getJSONObject(i).toString(), Post.class);
                    ps.setInt(1, post.getUserId());
                    ps.setInt(2, post.getId());
                    ps.setString(3, post.getTitle());
                    ps.setString(4, post.getBody());
                    ps.addBatch();
                }
                int i[] = ps.executeBatch();
                System.out.println(i.length);
            } catch (Exception e) {
                System.out.println(e);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton b = (JButton) e.getSource();
        setBackgroundColor(e.getActionCommand());
        b.setBackground(Color.GREEN);
        call(b.getActionCommand());
    }

    private void call(String id) {
        DefaultTableModel dt = (DefaultTableModel) table.getModel();
        int allrow = dt.getRowCount();
        if (allrow > 0) {
            deleteAllRow(dt);
        }

        for (Post post : getData((Integer.parseInt(id) - 1) * perpage, perpage)) {
            dt.addRow(new Object[] { post.getId(), post.getTitle(), post.getBody() });
        }
    }

    private void deleteAllRow(DefaultTableModel dt) {
        int allrow = dt.getRowCount();
        for (int i = allrow - 1; i >= 0; i--) {
            dt.removeRow(i);
        }
    }

    private void setBackgroundColor(String id) {
        for (JButton b : buttons) {
            if (!b.getActionCommand().equals(id)) {
                b.setBackground(Color.red);
            }
        }
    }
}

Frequently Asked Questions

What is pagination in Java Swing?

Pagination in Java Swing is the process of dividing a large result set into smaller chunks (pages) and displaying one page at a time in a JTable. It uses SQL LIMIT with OFFSET to fetch only the required rows per page.

How do I fetch paginated data from MySQL in Java?

Use the SQL LIMIT clause with two parameters: select * from table limit ?,? where the first parameter is the starting row (page - 1) * perPage and the second is the number of rows per page.

How do I load live JSON data into a MySQL table in Java?

Open an HTTP connection to the JSON API with HttpURLConnection, read the response with a BufferedReader, parse it with Gson into Java objects, and insert them into MySQL using PreparedStatement batch inserts.

Why does the pagination tutorial show uppercase titles?

The tutorial uses toUpperCase(Locale.getDefault()) on the title and body fields when reading from the database. This is optional — you can remove it to display the original case.

Can I use this pagination example with PostgreSQL or Oracle?

Yes, but the SQL LIMIT syntax differs. PostgreSQL supports LIMIT and OFFSET similarly. Oracle uses ROWNUM or the OFFSET ... FETCH NEXT syntax. Only the SQL query needs to change, not the Java logic.

Conclusion

In this tutorial, you built a complete pagination example in Java Swing. You learned how to:

  • Fetch live JSON data from a REST API using HttpURLConnection
  • Parse JSON with Gson and insert it into MySQL in batch
  • Count total rows to calculate the number of pages
  • Fetch only a subset of rows per page using SQL LIMIT
  • Build dynamic page buttons and highlight the active page

Related topics: Java Swing JTable Tutorial, JDBC Batch Insert, Gson JSON Parsing, MySQL LIMIT and OFFSET, Java HTTPURLConnection, Swing Event Handling

No comments: