How do I create a simple JTable component?

The code snippet presented below shows you how to create a simple JTable component in a swing application. To create a JTable component we initialize it using the constructor that accept two parameters.

The first parameter is the table’s row of data which type is Object[][], a two-dimensional array of Object. The second parameter is the table’s column names which type is Object[], an array of object.

After the JTable instance is created we place it inside a scroll pane component which in turn is added to the frame’s content pane.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.text.MessageFormat;
import java.util.Calendar;

public class SimpleJTableDemo extends JFrame {
    public SimpleJTableDemo() throws HeadlessException {
        initializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new SimpleJTableDemo().setVisible(true));
    }

    private void initializeUI() {
        // Defines table's column names.
        String[] columnNames = {
                "ID", "Name", "Date of Birth", "Sex"
        };

        // Defines table's data.
        Object[][] rowData = {
                {1, "Alice", createDOB(1980, Calendar.JANUARY, 1), "F"},
                {2, "Bob", createDOB(1982, Calendar.JUNE, 21), "M"},
                {3, "Carol", createDOB(1970, Calendar.OCTOBER, 12), "M"},
                {4, "Mallory", createDOB(1988, Calendar.FEBRUARY, 19), "M"}
        };

        // Initializes an instance of JTable and specifies the table
        // data and column names. Then we place the table in a scroll pane.
        JTable table = new JTable(rowData, columnNames);
        JScrollPane pane = new JScrollPane(table);

        // Sets the frame setting.
        setTitle("Simple JTable Demo");
        setSize(new Dimension(500, 500));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        getContentPane().add(pane, BorderLayout.CENTER);
    }

    private String createDOB(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return MessageFormat.format("{0,date,dd-MMM-yyyy}", calendar.getTime());
    }
}

When we run the program we will see the following result:

Simple JTable Demo

Simple JTable Demo

Wayan

Leave a Reply

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