How do I display data in a JTable in Java Swing?

Use a JTable to display data in rows and columns. A table model provides the data, column names, and rules for editing cells.

In this example, you will display a read-only book catalog with three columns: Title, Author, and Pages.

Source code

Save the following code as TableExample.java:

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class TableExample {
    void main() {
        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        String[] columns = {"Title", "Author", "Pages"};
        Object[][] books = {
                {"Learning Java", "Alice", 240},
                {"Exploring Java", "Bob", 180},
                {"Building Java Apps", "Carol", 320}
        };

        DefaultTableModel model = new DefaultTableModel(books, columns) {
            @Override
            public Class<?> getColumnClass(int column) {
                return column == 2 ? Integer.class : String.class;
            }

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        JTable table = new JTable(model);
        table.setPreferredScrollableViewportSize(new Dimension(420, 120));

        JFrame frame = new JFrame("Book Catalog");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JScrollPane(table));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Illustration of a Book Catalog window with three rows and columns for title, author, and page count

Explanation

Each row in the books array represents one book. The values follow the same order as the column names. The array uses Object[][] because each row contains both text and a number.

DefaultTableModel supplies the rows and column names to JTable. The example overrides two methods:

Method What it does
getColumnClass() Tells Swing that column 2 (the third column) contains Integer values. The first two columns contain String values. Swing uses these types to choose how to display each cell.
isCellEditable() Returns false for every cell, so users can select cells but cannot edit them through the table.

Adding new JScrollPane(table) to the frame displays the column headers and lets users scroll if the rows do not fit. The preferred viewport size gives the table a starting size when frame.pack() sizes the window.

Run the example

javac TableExample.java
java TableExample

The Book Catalog window displays all three books. Try double-clicking a title: the cell can be selected, but it does not open for editing.

Wayan

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.