How do I create a scrollable JTable component?

To create a scrollable JTable component we have to use a JScrollPane as the container of the JTable. Beside that we also need to set the table auto resize mode to JTable.AUTO_RESIZE_OFF so that a horizontal scroll bar displayed by the scroll pane when needed. If we do not turn off the auto resize mode the columns of the table will be resized to fit the available window size.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;

public class ScrollableJTable extends JPanel {
    public ScrollableJTable() {
        initializeUI();
    }

    private void initializeUI() {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(400, 200));

        JTable table = new JTable(20, 20);

        // Turn off JTable's auto resize so that JScrollPane will show a horizontal
        // scroll bar.
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        JScrollPane pane = new JScrollPane(table);
        add(pane, BorderLayout.CENTER);
    }

    private static void showFrame() {
        JPanel panel = new ScrollableJTable();
        panel.setOpaque(true);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setTitle("Scrollable JTable");
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                ScrollableJTable.showFrame();
            }
        });
    }
}

How do I get the selected cells in JTable component?

The following examples shows you how to get the selected rows or the selected columns or the selection of multiple cells in the JTable component. To listen for selection event we can add a selection listener to JTable component by calling the JTable.getSelectionModel().addListSelectionListener() method. This method accepts an object which implements a ListSelectionListener interface.`

package org.kodejava.example.swing;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

public class JTableGetSelectedCells extends JPanel {
    private JTable table = null;

    public JTableGetSelectedCells() {
        initializePanel();
    }

    private void initializePanel() {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(500, 200));

        table = new JTable(new PremiereLeagueTableModel());
        table.getColumnModel().getColumn(0).setMinWidth(150);
        table.getSelectionModel().addListSelectionListener(
                new RowColumnListSelectionListener());

        table.setFillsViewportHeight(true);
        JScrollPane pane = new JScrollPane(table);

        JPanel control = new JPanel(new FlowLayout());
        final JCheckBox cb1 = new JCheckBox("Row Selection");
        final JCheckBox cb2 = new JCheckBox("Columns Selection");
        final JCheckBox cb3 = new JCheckBox("Cells Selection");

        // Change row selection allowed state
        cb1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                table.setRowSelectionAllowed(cb1.isSelected());
                table.setColumnSelectionAllowed(!cb1.isSelected());

                cb2.setSelected(!cb1.isSelected());
            }
        });

        // Change column selection allowed state
        cb2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                table.setColumnSelectionAllowed(cb2.isSelected());
                table.setRowSelectionAllowed(!cb2.isSelected());
                cb1.setSelected(!cb2.isSelected());
            }
        });

        // Enable cell selection
        cb3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                table.setCellSelectionEnabled(cb3.isSelected());
                table.setRowSelectionAllowed(cb3.isSelected());
                table.setColumnSelectionAllowed(cb3.isSelected());
            }
        });

        control.add(cb1);
        control.add(cb2);
        control.add(cb3);

        add(pane, BorderLayout.CENTER);
        add(control, BorderLayout.SOUTH);
    }

    private class RowColumnListSelectionListener implements ListSelectionListener {
        public void valueChanged(ListSelectionEvent e) {
            if (table.getRowSelectionAllowed() &&
                    !table.getColumnSelectionAllowed()) {
                int[] rows = table.getSelectedRows();
                System.out.println("Selected Rows: " + Arrays.toString(rows));
            }
            if (table.getColumnSelectionAllowed() &&
                    !table.getRowSelectionAllowed()) {
                int[] cols = table.getSelectedColumns();
                System.out.println("Selected Columns: " + Arrays.toString(cols));
            } else if (table.getCellSelectionEnabled()) {
                int selectionMode = table.getSelectionModel().getSelectionMode();
                System.out.println("selectionMode = " + selectionMode);
                if (selectionMode == ListSelectionModel.SINGLE_SELECTION) {
                    int rowIndex = table.getSelectedRow();
                    int colIndex = table.getSelectedColumn();
                    System.out.printf("Selected [Row,Column] = [%d,%d]\n", rowIndex, colIndex);
                } else if (selectionMode == ListSelectionModel.SINGLE_INTERVAL_SELECTION ||
                        selectionMode == ListSelectionModel.MULTIPLE_INTERVAL_SELECTION) {
                    int rowIndexStart = table.getSelectedRow();
                    int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
                    int colIndexStart = table.getSelectedColumn();
                    int colIndexEnd = table.getColumnModel().getSelectionModel().getMaxSelectionIndex();

                    for (int i = rowIndexStart; i <= rowIndexEnd; i++) {
                        for (int j = colIndexStart; j <= colIndexEnd; j++) {
                            if (table.isCellSelected(i, j)) {
                                System.out.printf("Selected [Row,Column] = [%d,%d]\n", i, j);
                            }
                        }
                    }
                }
            }
        }
    }

    public static void showFrame() {
        JPanel panel = new JTableGetSelectedCells();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTable Selected Cells Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                showFrame();
            }
        });
    }

    class PremiereLeagueTableModel extends AbstractTableModel {
        // TableModel's column names
        private String[] columnNames = {
                "TEAM", "P", "W", "D", "L", "GS", "GA", "GD", "PTS"
        };

        // TableModel's data
        private Object[][] data = {
                {"Chelsea", 5, 5, 0, 0, 21, 1, 20, 15},
                {"Arsenal", 5, 3, 2, 0, 14, 4, 10, 11},
                {"Manchester United", 5, 3, 2, 0, 14, 7, 7, 11},
                {"Manchester City", 5, 2, 2, 1, 6, 2, 4, 8},
                {"Tottenham Hotspur", 5, 2, 2, 1, 6, 4, 2, 8}
        };

        public int getRowCount() {
            return data.length;
        }

        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            return data[rowIndex][columnIndex];
        }
    }
}

When you run the program you will see the following screen. Selecting some cells in the JTable will print the selected rows, the selected columns or some indexes of selected rows and columns in ListSelectionModel.MULTIPLE_INTERVAL_SELECTION selection mode.

JTable Selected Row Column Cells Demo

How do I programmatically select JTable’s rows?

This program shows you how to select some rows in the JTable programmatically. Below we demonstrates how to select rows using the setRowSelectionInterval() method, remove or clear row selection using removeRowSelectionInterval() method and use the addRowSelectionInterval() to add more rows to the previously selected rows.

package org.kodejava.example.swing;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JTableRowSelectProgrammatically extends JPanel {
    public JTableRowSelectProgrammatically() {
        initializePanel();
    }

    private void initializePanel() {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(475, 250));

        final JTable table = new JTable(new MyTableModel());
        table.setFillsViewportHeight(true);
        JScrollPane pane = new JScrollPane(table);

        JLabel label1 = new JLabel("From row: ");
        final JTextField field1 = new JTextField(3);
        JLabel label2 = new JLabel("To row: ");
        final JTextField field2 = new JTextField(3);
        JButton select = new JButton("Select");
        JButton clear = new JButton("Clear");
        JButton add = new JButton("Add another one");

        // Enables row selection mode and disable column selection
        // mode.
        table.setRowSelectionAllowed(true);
        table.setColumnSelectionAllowed(false);

        // Select rows based on the input.
        select.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                int index1 = 0;
                int index2 = 0;
                try {
                    index1 = Integer.valueOf(field1.getText());
                    index2 = Integer.valueOf(field2.getText());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

                if (index1 < 0 || index2 < 0 ||
                    index1 >= table.getRowCount() ||
                    index2 >= table.getRowCount()) {
                    JOptionPane.showMessageDialog(table, "Selection out of range!");
                } else {
                    table.setRowSelectionInterval(index1, index2);
                }
            }
        });

        // Clears row selection
        clear.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                table.removeRowSelectionInterval(0, table.getRowCount() - 1);
                field1.setText("");
                field2.setText("");
            }
        });

        // Add one more row after the last selected row.
        add.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                int index2 = 0;
                try {
                    index2 = Integer.valueOf(field2.getText());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

                index2 = index2 + 1;
                table.addRowSelectionInterval(index2, index2);
                field2.setText(String.valueOf(index2));
            }
        });

        JPanel command = new JPanel(new FlowLayout());
        command.add(label1);
        command.add(field1);
        command.add(label2);
        command.add(field2);
        command.add(select);
        command.add(clear);
        command.add(add);

        add(pane, BorderLayout.CENTER);
        add(command, BorderLayout.SOUTH);
    }

    public static void showFrame() {
        JPanel panel = new JTableRowSelectProgrammatically();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTable Row Selection");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JTableRowSelectProgrammatically.showFrame();
            }
        });
    }

    public class MyTableModel extends AbstractTableModel {
        private String[] columns = {"ID", "NAME", "AGE", "A STUDENT?"};
        private Object[][] data = {
            {1, "Alice", 20, Boolean.FALSE},
            {2, "Bob", 10, Boolean.TRUE},
            {3, "Carol", 15, Boolean.TRUE},
            {4, "Ignasia", 20, Boolean.TRUE},
            {5, "Mallory", 25, Boolean.FALSE}
        };

        public int getRowCount() {
            return data.length;
        }

        public int getColumnCount() {
            return columns.length;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            return data[rowIndex][columnIndex];
        }

        @Override
        public String getColumnName(int column) {
            return columns[column];
        }

        // This method is used by the JTable to define the default
        // renderer or editor for each cell. For example if you have
        // a boolean data it will be rendered as a check box. A
        // number value is right aligned.
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return data[0][columnIndex].getClass();
        }
    }
}

Below is the screen capture of the program.

Programmatically Select JTable Rows

How do I set the JTable’s selection mode?

There are three selection modes available in the JTable component. The selection mode can be a single selection, a single interval selection or a multiple interval selection. To set the selection mode we call the JTable.setSelectionMode() method and pass one of the following value as the parameter:

  • ListSelectionModel.SINGLE_SELECTION
  • ListSelectionModel.SINGLE_INTERVAL_SELECTION
  • ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
package org.kodejava.example.swing;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;

public class TableSelectionModeDemo extends JPanel {
    public TableSelectionModeDemo() {
        initializePanel();
    }

    private void initializePanel() {
        this.setLayout(new BorderLayout());

        JTable table = new JTable(new PremiereLeagueTableModel());

        // Settings table selection mode. We can use the following
        // three constants to define the selection mode.
        //
        // - ListSelectionModel.SINGLE_SELECTION
        // - ListSelectionModel.SINGLE_INTERVAL_SELECTION
        // - ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        JScrollPane pane = new JScrollPane(table);
        this.add(pane, BorderLayout.CENTER);
        this.setPreferredSize(new Dimension(500, 150));
    }

    public static void showFrame() {
        JPanel panel = new TableSelectionModeDemo();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTable Single Selection");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                TableSelectionModeDemo.showFrame();
            }
        });
    }

    class PremiereLeagueTableModel extends AbstractTableModel {
        // TableModel's column names
        private String[] columnNames = {
            "TEAM", "P", "W", "D", "L", "GS", "GA", "GD", "PTS"
        };

        // TableModel's data
        private Object[][] data = {
            { "Liverpool", 3, 3, 0, 0, 7, 0, 7, 9 },
            { "Tottenham", 3, 3, 0, 0, 8, 2, 6, 9 },
            { "Chelsea", 3, 3, 0, 0, 8, 3, 5, 9 },
            { "Watford", 3, 3, 0, 0, 7, 2, 5, 9 },
            { "Manchester City", 3, 2, 1, 0, 9, 2, 7, 7 }
        };

        public int getRowCount() {
            return data.length;
        }

        public int getColumnCount() {
            return columnNames.length;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            return data[rowIndex][columnIndex];
        }
    }
}

JTable Selection Mode Demo

How do I allow row or column selection in JTable?

To allow a row selection or a column selection or both row and column selection in JTable component we can turn it on and off by calling the JTable‘s setRowSelectionAllowed() and JTable‘s setColumnSelectionAllowed() methods.

Both of these method accept a boolean value indicating whether the selection is allowed or not allowed. Setting both of them to true allow us to select rows and columns from JTable.

package org.kodejava.example.swing;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;

public class TableAllowColumnSelection extends JPanel {
    public TableAllowColumnSelection() {
        initializePanel();
    }

    private void initializePanel() {
        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(500, 150));

        JTable table = new JTable(new PremiereLeagueTableModel());
        // sets to false to disallow row selection in the table
        // model.
        table.setRowSelectionAllowed(false);

        // Sets to true to allow column selection in the table
        // model.
        table.setColumnSelectionAllowed(true);

        JScrollPane pane = new JScrollPane(table);
        this.add(pane, BorderLayout.CENTER);
    }

    public static void showFrame() {
        JPanel panel = new TableAllowColumnSelection();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTable Column Selection");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                TableAllowColumnSelection.showFrame();
            }
        });
    }

    class PremiereLeagueTableModel extends AbstractTableModel {
        // TableModel's column names
        private String[] columnNames = {
            "TEAM", "P", "W", "D", "L", "GS", "GA", "GD", "PTS"
        };

        // TableModel's data
        private Object[][] data = {
            { "Liverpool", 3, 3, 0, 0, 7, 0, 7, 9 },
            { "Tottenham", 3, 3, 0, 0, 8, 2, 6, 9 },
            { "Chelsea", 3, 3, 0, 0, 8, 3, 5, 9 },
            { "Watford", 3, 3, 0, 0, 7, 2, 5, 9 },
            { "Manchester City", 3, 2, 1, 0, 9, 2, 7, 7 }
        };

        public int getRowCount() {
            return data.length;
        }

        public int getColumnCount() {
            return columnNames.length;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            return data[rowIndex][columnIndex];
        }
    }
}

JTable Row and Column Selection

How do I set or change JTable column width?

Each column of a JTable component is represented by the TableColumn class. The method for setting or changing the width of the column includes the setMinWidth(), setMaxWidth() and setPreferredWidth(). These methods is used to set the minimum, maximum and the preferred width of the column respectively.

When we set only the preferred width of a table column and the container get resized the preferred width will be used to recalculate the new column width to fill the available space, but the preferred width value itself does not change.

TableColumn object of a table can be obtained by calling table’s getColumnModel() method which return an instance of TableColumnModel. After having the TableColumModel in hand we can get the table’s column by calling the getColumn(int index) method and passes the index of the column.

package org.kodejava.example.swing;

import javax.swing.*;
import javax.swing.table.TableColumn;
import java.awt.*;

public class TableColumnWidthDemo extends JPanel {
    public TableColumnWidthDemo() {
        initializePanel();
    }

    private void initializePanel() {
        // Defines table's column names.
        String[] columnNames = {
            "TEAM", "P", "W", "D", "L", "GS", "GA", "GD", "PTS"
        };

        // Defines table's data.
        Object[][] data = {
            { "Liverpool", 3, 3, 0, 0, 7, 0, 7, 9 },
            { "Tottenham", 3, 3, 0, 0, 8, 2, 6, 9 },
            { "Chelsea", 3, 3, 0, 0, 8, 3, 5, 9 },
            { "Watford", 3, 3, 0, 0, 7, 2, 5, 9 },
            { "Manchester City", 3, 2, 1, 0, 9, 2, 7, 7 }
        };

        // Defines table's column width.
        int[] columnsWidth = {
            200, 25, 25, 25, 25, 25, 25, 25, 50
        };

        // Creates an instance of JTable and fill it with data and
        // column names information.
        JTable table = new JTable(data, columnNames);

        // Configures table's column width.
        int i = 0;
        for (int width : columnsWidth) {
            TableColumn column = table.getColumnModel().getColumn(i++);
            column.setMinWidth(width);
            column.setMaxWidth(width);
            column.setPreferredWidth(width);
        }

        JScrollPane scrollPane = new JScrollPane(table);
        table.setFillsViewportHeight(true);
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
        this.setPreferredSize(new Dimension(500, 200));
    }

    public static void showFrame() {
        JPanel panel = new TableColumnWidthDemo();
        panel.setOpaque(true);

        // Creates and configures the JFrame component for our
        // program.
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.setTitle("English Premiere League - 2018/2019");
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                showFrame();
            }
        });
    }
}

Here is the table created by the program above:

JTable Column Width Demo

How do I create a table model for JTable component?

Another way to create and configure a JTable component is using a table model. A table model is more preferred to using array or vector as the data source for the table.

The simplest way to create a table model is by extending the AbstractTableModel abstract class which implements the TableModel interface. The AbstractTableModel implements the standard behaviour of a table model. It implements almost all the methods of the TableModel interface, except three methods.

These three methods are the getValueAt(int rowIndex, int columnIndex) method, the getRowCount() method and the getColumnCount() method. The code below show you how to create a table model.

package org.kodejava.example.swing;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;

public class TableModelDemo extends JPanel {
    public TableModelDemo() {
        initializePanel();
    }

    private void initializePanel() {
        // Creates an instance of PremiereLeagueTableModel
        PremiereLeagueTableModel tableModel =
            new PremiereLeagueTableModel();

        // Creates an instance of JTable with a TableModel
        // as the constructor parameters.
        JTable table = new JTable(tableModel);
        table.setFillsViewportHeight(true);
        JScrollPane scrollPane = new JScrollPane(table);

        this.setPreferredSize(new Dimension(500, 200));
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
    }

    public static void showFrame() {
        JPanel panel = new TableModelDemo();
        panel.setOpaque(true);

        JFrame frame = new JFrame("Premiere League - 2018/2019");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    class PremiereLeagueTableModel extends AbstractTableModel {
        // TableModel's column names
        private String[] columnNames = {
            "TEAM", "P", "W", "D", "L", "GS", "GA", "GD", "PTS"
        };

        // TableModel's data
        private Object[][] data = {
            { "Liverpool", 3, 3, 0, 0, 7, 0, 7, 9 },
            { "Tottenham", 3, 3, 0, 0, 8, 2, 6, 9 },
            { "Chelsea", 3, 3, 0, 0, 8, 3, 5, 9 },
            { "Watford", 3, 3, 0, 0, 7, 2, 5, 9 },
            { "Manchester City", 3, 2, 1, 0, 9, 2, 7, 7 }
        };

        /**
         * Returns the number of rows in the table model.
         */
        public int getRowCount() {
            return data.length;
        }

        /**
         * Returns the number of columns in the table model.
         */
        public int getColumnCount() {
            return columnNames.length;
        }

        /**
         * Returns the column name for the column index.
         */
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

        /**
         * Returns data type of the column specified by its index.
         */
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return getValueAt(0, columnIndex).getClass();
        }

        /**
         * Returns the value of a table model at the specified
         * row index and column index.
         */
        public Object getValueAt(int rowIndex, int columnIndex) {
            return data[rowIndex][columnIndex];
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                showFrame();
            }
        });
    }
}

JTable’s TableModel Demo

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 initializes 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 places it inside a scroll pane component which in turn is added to the frame’s content pane.

package org.kodejava.example.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();
    }

    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"},
            {5, "Ignasia", createDOB(1984, Calendar.NOVEMBER, 28), "F"}
        };

        // Initializes an instance of JTable and specifies the table
        // data and column names. After that 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(400, 200));
        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());
    }

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

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

Simple JTable Demo