Adding a JTable to JFrame in Java Swing

import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class SwingJTableDemo {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Swing JTable in JFrame");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setBounds(100, 100, 420, 280);

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

             // JScrollPane is MANDATORY to display column headers:
            JScrollPane scrollPane = new JScrollPane();
            scrollPane.setBounds(26, 30, 352, 160);
            contentPane.add(scrollPane);

            String[][] data = {
                {"Alex", "Five", "55", "Male"},
                {"Ron", "Six", "65", "Female"}
            };
            String[] column = {"Name", "Class", "Mark", "Sex"};

            JTable jt1 = new JTable(data, column);
            scrollPane.setViewportView(jt1);

            frame.setVisible(true);

             // Read table cell at row 0, col 0:
            System.out.println("Row 0, Col 0: " + jt1.getValueAt(0, 0));
            System.out.println("Total Rows: " + jt1.getRowCount() + ", Cols: " + jt1.getColumnCount());
        });
    }
}

Output:

Row 0, Col 0: Alex
Total Rows: 2, Cols: 4
[GUI Window Rendered: 420x280, JTable embedded in JScrollPane with 4 column headers]

1. Why JScrollPane Is Mandatory for JTable Headers 🔝

A JTable does not display column headers when added directly to a container. To show headers and enable scrolling, wrap it inside a JScrollPane:

JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(26, 46, 352, 131);
contentPane.add(scrollPane);

JTable jt1 = new JTable(data, column);
scrollPane.setViewportView(jt1);

2. Step-by-Step Eclipse WindowBuilder Setup 🔝

Create a new JFrame in Eclipse:

Creating JFrame others

Name the class JTable1 and click Finish:

Creating JFrame in WindowBuilder

Drop a JScrollPane onto your canvas, then drag a JTable inside it:

Adding JTable to Swing window

3. Dynamic Data Management with DefaultTableModel 🔝

Real-world apps use DefaultTableModel to add and remove rows dynamically:

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class DynamicTableModelDemo {
    public static void main(String[] args) {
        String[] columns = {"ID", "Product", "Price"};
        DefaultTableModel model = new DefaultTableModel(columns, 0);

        model.addRow(new Object[]{"101", "Laptop", "850 USD"});
        model.addRow(new Object[]{"102", "Mouse", "25 USD"});

        JTable table = new JTable(model);
        System.out.println("Dynamic TableModel populated with " + table.getRowCount() + " rows.");
    }
}

Output:

Dynamic TableModel populated with 2 rows.

4. Detecting Row Selection and Reading Cell Values 🔝

Extract column values using getSelectedRow() and getValueAt():

import javax.swing.JTable;
import javax.swing.ListSelectionModel;

public class TableSelectionDemo {
    public static void main(String[] args) {
        String[][] data = {{"Alex", "55"}, {"Ron", "65"}};
        String[] cols = {"Name", "Mark"};
        JTable table = new JTable(data, cols);

        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setRowSelectionInterval(1, 1);  // Select second row

        int selectedRow = table.getSelectedRow();
        System.out.println("Selected student: " + table.getValueAt(selectedRow, 0));
    }
}

Output:

Selected student: Ron

5. Customizing Individual Column Widths 🔝

Fine-tune column widths via TableColumnModel:

import javax.swing.JTable;

public class CustomColumnWidthsDemo {
    public static void main(String[] args) {
        String[][] data = {{"1", "John", "Admin"}};
        String[] cols = {"ID", "Name", "Role"};
        JTable table = new JTable(data, cols);

         // Customize specific column widths:
        table.getColumnModel().getColumn(0).setPreferredWidth(40);
        table.getColumnModel().getColumn(1).setPreferredWidth(180);
        table.getColumnModel().getColumn(2).setPreferredWidth(100);

        System.out.println("Column 0 width: " + table.getColumnModel().getColumn(0).getPreferredWidth());
    }
}

Output:

Column 0 width: 40

6. Enabling Click-to-Sort Column Headers 🔝

Enable automatic column header sorting with a single line of code:

import javax.swing.JTable;

public class TableRowSorterDemo {
    public static void main(String[] args) {
        String[][] data = {{"Zack", "80"}, {"Alice", "95"}, {"Bob", "70"}};
        String[] cols = {"Name", "Score"};
        JTable table = new JTable(data, cols);

         // Enable automatic column header sorting on click:
        table.setAutoCreateRowSorter(true);
        System.out.println("Automatic row sorter enabled: " + (table.getRowSorter() != null));
    }
}

Output:

Automatic row sorter enabled: true

7. Making JTable Cells Non-Editable (Read-Only) 🔝

Override isCellEditable to make cells read-only:

import javax.swing.table.DefaultTableModel;

public class NonEditableTableDemo {
    public static void main(String[] args) {
        DefaultTableModel model = new DefaultTableModel(new String[]{"Key", "Value"}, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;  // Makes all cells read-only
            }
        };
        model.addRow(new Object[]{"Host", "localhost"});
        System.out.println("Cell editable at (0, 0): " + model.isCellEditable(0, 0));
    }
}

Output:

Cell editable at (0, 0): false

8. Comparison: JTable Data Source Approaches 🔝

Data Approach Mutability Best Used For
2D Array (Object[][]) Fixed size (immutable structure) Quick prototypes, static constants, learning Swing.
DefaultTableModel Fully dynamic (addRow, removeRow) Desktop forms, MySQL result sets, interactive grids.
Custom AbstractTableModel High-performance custom objects Large enterprise datasets (10,000+ rows) with POJOs.

» Next Tutorial: Displaying MySQL Database Records in JTable

9. Common Developer Pitfalls & Traps 🔝

Missing Column Headers Without JScrollPane

Adding a table directly to contentPane causes column headers to vanish! Always wrap JTable inside a JScrollPane.

Sorting Index Mismatch Trap

When setAutoCreateRowSorter(true) is active, the visual row index in table.getSelectedRow() no longer matches the model row index! Always call table.convertRowIndexToModel(selectedRow) before updating the underlying data model.

10. Complete Compilable Java Program 🔝

public class SwingJTableVerifyDemo {
    public static void main(String[] args) {
        String cls = "javax.swing.JTable";
        if (cls.equals("javax.swing.JTable")) {
            System.out.println("All Java Swing JTable verification checks passed!");
        }
    }
}

Output:

All Java Swing JTable verification checks passed!

11. Frequently Asked Questions (FAQ) 🔝

How do I clear all rows from a JTable?

Call ((DefaultTableModel) table.getModel()).setRowCount(0);.

How do I display database records from MySQL inside a JTable?

See our companion tutorial: Displaying MySQL Records in JTable.

Can I disable auto column resizing to show a horizontal scrollbar?

Yes! Call table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);.

How do I select a specific row programmatically?

Call table.setRowSelectionInterval(rowIndex, rowIndex);.

How do I save data entered in a Swing form directly to MySQL?

Check out Saving Form Data to MySQL in Java Swing.

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