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.swing;

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

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

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

        JFrame frame = new JFrame("Premiere League - Season 2021-2022");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TableModelDemo::showFrame);
    }

    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);
        TableColumnModel columnModel = table.getColumnModel();
        columnModel.getColumn(0).setPreferredWidth(200);

        JScrollPane scrollPane = new JScrollPane(table);

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

    static class PremiereLeagueTableModel extends AbstractTableModel {
        // TableModel's column names
        private final String[] columnNames = {
                "CLUB", "MP", "W", "D", "L", "GF", "GA", "GD", "PTS"
        };

        // TableModel's data
        private final Object[][] data = {
                {"Chelsea", 8, 6, 1, 1, 16, 3, 13, 19},
                {"Liverpool", 8, 5, 3, 0, 22, 6, 16, 18},
                {"Manchester City", 8, 5, 2, 1, 16, 3, 13, 17},
                {"Brighton", 8, 4, 3, 1, 8, 5, 3, 15},
                {"Tottenham", 8, 5, 0, 3, 9, 12, -3, 15}
        };

        /**
         * 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];
        }
    }
}
JTable TableModel Demo

JTable 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 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

How do I set the initial color of a JColorChooser?

To create an instance of a JColorChooser with a default or initial color such as Color.BLUE you can pass the Color object to the constructor of the JColorChooser component. The example below shows how to do it.

package org.kodejava.swing;

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

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

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

    private void initializeUI() {
        setTitle("JColorChooser Demo");
        setLayout(new BorderLayout());
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        // Creates an instance of JColorChooser and set Color.BLUE
        // as the default selected color.
        JColorChooser jcc = new JColorChooser(Color.BLUE);

        getContentPane().add(jcc, BorderLayout.CENTER);
        this.pack();
    }
}

JColorChooser Initial Color

How do I get the selected color from JColorChooser?

To get the selected color from JColorChooser we need to create an implementation of the ChangeListener interface. This interface provides a single method call stateChanged(ChangeEvent e). The instance of this interface implementation need to be passed to JColorChooser by calling the JColorChooser.getSelectionModel().addChangeListener() method.

In this example our ChangeListener implementation get the selected color and replace the foreground color the JLabel component.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;

public class JColorChooserColorSelection extends JFrame {
    private JColorChooser jcc = null;
    private JLabel label = null;

    public JColorChooserColorSelection() {
        initializeUI();
    }

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

    private void initializeUI() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        jcc = new JColorChooser();
        jcc.getSelectionModel().addChangeListener(new ColorSelection());
        getContentPane().add(jcc, BorderLayout.PAGE_START);

        label = new JLabel("Selected Font Color", JLabel.CENTER);
        label.setFont(new Font("SansSerif", Font.BOLD, 24));
        label.setForeground(Color.BLACK);
        label.setPreferredSize(new Dimension(100, 100));
        getContentPane().add(label, BorderLayout.CENTER);
        this.pack();
    }

    /**
     * A ChangeListener implementation for listening the color
     * selection of the JColorChooser component.
     */
    class ColorSelection implements ChangeListener {
        public void stateChanged(ChangeEvent e) {
            Color color = jcc.getColor();
            label.setForeground(color);
        }
    }
}

JColorChooser get selected color

How do I use JColorChooser component?

The JColorChooser is a Swing component that provides a palette from where we can select a color code in RGB format. The JColorChooser component has two parts, the tabbed pane of color selection and a preview box. The tabbed has three tabs which allows us to select a color from a swatches, a HSB (Hue, Saturation and Brightness) combination and an RGB (Red Blue Green) color combination.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;

public class JColorChooserDemo extends JFrame implements ChangeListener {
    private JColorChooser colorChooser = null;

    public JColorChooserDemo() throws HeadlessException {
        initUI();
    }

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

    private void initUI() {
        // Set title and default close operation of this JFrame.
        setTitle("JColorChooser Demo");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // Creates an instance of JColorChooser component and
        // adds it to the frame's content.
        colorChooser = new JColorChooser();
        getContentPane().add(colorChooser, BorderLayout.PAGE_END);

        // Add a change listener to get the selected color in this
        // JColorChooser component.
        colorChooser.getSelectionModel().addChangeListener(this);
        this.pack();
    }

    /**
     * Handles color selection in the JColorChooser component.
     *
     * @param e the ChangeEvent
     */
    public void stateChanged(ChangeEvent e) {
        // Get the selected color in the JColorChooser component
        // and print the color in RGB format to the console.
        Color color = colorChooser.getColor();
        System.out.println("color = " + color);
    }
}

When you run the program above a frame with JColorChooser component will be shown. A string of the color code in an RGB format will be printed in the console if you click a color from the color selection.

Here is an image of a JColorChooser component.

JColorChooser Component Demo