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

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

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

    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("Premiere League - Season 2021-2022");
        frame.pack();
        frame.setVisible(true);
    }

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

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

        // Defines table's data.
        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}
        };

        // 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, 500));
    }
}

Here is the table created by the program above:

JTable Column Width Demo

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