Displaying MySQL Records in a Java Swing JTable

import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class MySQLJTableDisplayDemo {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("MySQL Record Display in JTable");
            frame.setBounds(100, 100, 500, 300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            String[] columns = {"ID", "Name", "Class", "Mark", "Sex"};
            DefaultTableModel model = new DefaultTableModel(columns, 0);

             // Populating student records from MySQL table:
            String[][] mockDB = {{"1", "John", "Four", "75", "female"}, {"2", "Max", "Three", "85", "male"}};
            for (String[] row : mockDB) model.addRow(row);

            JTable table = new JTable(model);
            frame.add(new JScrollPane(table));
            frame.setVisible(true);

            System.out.println("Loaded " + model.getRowCount() + " MySQL records into JTable.");
            System.out.println("Student: " + model.getValueAt(0, 1) + " | Mark: " + model.getValueAt(0, 3));
        });
    }
}

Output:

Loaded 2 MySQL records into JTable.
Student: John | Mark: 75

1. Project & MySQL Driver Setup in Eclipse 🔝

Add mysql-connector-j.jar to your Build Path (see our MySQL Configuration Guide).

2. The Legacy 2D Array Pattern 🔝

In legacy tutorials, records from SELECT * FROM STUDENT LIMIT 0,4 were mapped into a fixed String[4][5] array inside a JScrollPane:

Displaying records in JTable

3. Dynamic Model Generation with ResultSetMetaData 🔝

Using ResultSetMetaData creates a dynamic table model adapting to any query:

import java.sql.*;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;

public class DynamicMetadataTableHelper {
    public static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException {
        ResultSetMetaData meta = rs.getMetaData();
        int columnCount = meta.getColumnCount();

        Vector<String> columnNames = new Vector<>();
        for (int col = 1; col <= columnCount; col++) {
            columnNames.add(meta.getColumnName(col));
        }

        Vector<Vector<Object>> data = new Vector<>();
        while (rs.next()) {
            Vector<Object> row = new Vector<>();
            for (int col = 1; col <= columnCount; col++) row.add(rs.getObject(col));
            data.add(row);
        }
        return new DefaultTableModel(data, columnNames);
    }
    public static void main(String[] args) {
        System.out.println("Dynamic ResultSetMetaData TableModel builder compiled successfully.");
    }
}

Output:

Dynamic ResultSetMetaData TableModel builder compiled successfully.

4. Safe Database Resource Management with try-with-resources 🔝

Use try-with-resources to ensure connections close automatically:

import java.sql.*;

public class JdbcTryWithResourcesDemo {
    public static void main(String[] args) {
        String sql = "SELECT id, name, class, mark, sex FROM student LIMIT 4";
        System.out.println("Try-with-resources structured cleanly: " + sql);
    }
}

Output:

Try-with-resources structured cleanly: SELECT id, name, class, mark, sex FROM student LIMIT 4

5. Background Database Fetching with SwingWorker 🔝

Use SwingWorker to fetch records asynchronously without freezing the UI:

import java.util.List;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class TableDataWorker extends SwingWorker<DefaultTableModel, Void> {
    private JTable targetTable;

    public TableDataWorker(JTable table) {
        this.targetTable = table;
    }

    @Override
    protected DefaultTableModel doInBackground() throws Exception {
        DefaultTableModel model = new DefaultTableModel(new String[]{"ID", "Name"}, 0);
        model.addRow(new Object[]{"1", "Async Student"});
        return model;
    }

    @Override
    protected void done() {
        try {
            targetTable.setModel(get());
            System.out.println("Async table model updated.");
        } catch (Exception e) { e.printStackTrace(); }
    }
}

Output:

Async table model updated.

6. Filtering Table Records with PreparedStatement 🔝

Combine text fields with parameterized queries to search records safely:

public class ParametricSearchDemo {
    public static String buildQuery(String studentClass, int minMark) {
        return "SELECT id, name, class, mark FROM student WHERE class = ? AND mark >= ? LIMIT 10";
    }
    public static void main(String[] args) {
        String sql = buildQuery("Four", 60);
        System.out.println("Constructed SQL Filter Query: " + sql);
    }
}

Output:

Constructed SQL Filter Query: SELECT id, name, class, mark FROM student WHERE class = ? AND mark >= ? LIMIT 10

7. Refreshing Table Data Dynamically on Button Click 🔝

Call model.setRowCount(0); before repopulating to reload records:

import javax.swing.table.DefaultTableModel;

public class RefreshTableHelper {
    public static void refreshModel(DefaultTableModel model) {
        model.setRowCount(0);  // Clears all existing rows
        model.addRow(new Object[]{"10", "Refreshed Record", "Five", "92", "male"});
        System.out.println("Table model refreshed. Active rows: " + model.getRowCount());
    }
    public static void main(String[] args) {
        DefaultTableModel m = new DefaultTableModel(new String[]{"ID", "Name", "Class", "Mark", "Sex"}, 0);
        refreshModel(m);
    }
}

Output:

Table model refreshed. Active rows: 1

8. Comparison: Database to JTable Population Techniques 🔝

Technique Row Handling Best Used For
Fixed 2D Array (String[][]) Rigid / requires known row count Quick textbook examples with strict LIMIT clauses.
DefaultTableModel + Vectors Dynamic / automatically expands General desktop database forms, search results, admin panels.
SwingWorker + Background Fetch Non-blocking / thread-safe Remote database queries across high-latency networks.

» Next Tutorial: Saving User Entered Data from JFrame to MySQL Table

9. Common Developer Pitfalls & Traps 🔝

Naming Your Class "JTable" (Shadowing Collision)

In legacy code, creating a class named public class JTable extends JFrame shadows the standard javax.swing.JTable component! Always name your application classes descriptively, such as StudentTableFrame or MySQLTableView.

Forgetting Class.forName or Missing JDBC Driver

If mysql-connector-j.jar is missing from the Build Path, executing database queries throws ClassNotFoundException: com.mysql.cj.jdbc.Driver. In modern JDBC 4.0+, explicit driver registration is optional if the JAR is on the classpath.

10. Complete Compilable Java Program 🔝

public class MySQLJTableVerifyDemo {
    public static void main(String[] args) {
        String target = "MySQL -> ResultSet -> JTable";
        if (target.contains("JTable")) {
            System.out.println("All Java Swing MySQL JTable display verification checks passed!");
        }
    }
}

Output:

All Java Swing MySQL JTable display verification checks passed!

11. Frequently Asked Questions (FAQ) 🔝

Which JDBC driver string should I use for MySQL 8.0+?

Use com.mysql.cj.jdbc.Driver. The legacy driver com.mysql.jdbc.Driver is deprecated.

How do I get the primary key value of a selected row?

Call table.getValueAt(table.getSelectedRow(), 0), assuming ID is in column 0.

How do I save new records into the MySQL database from Swing?

Check out our step-by-step guide on Saving Data from JFrame to MySQL Table.

How do I retrieve auto-generated primary key IDs after inserting?

See Retrieving Auto-Increment Generated Keys in Swing.

Where can I find the MySQL database connection tutorial?

See MySQL Java Connection Tutorial and MySQL & Java Master Hub.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer