How do I render boolean value as checkbox in JTable component?

To make a JTable renders a boolean as a checkbox in the table cell we need to tell the table that a cell stores a boolean type of data. To do this we have to implement a TableModel for the JTable component.

TableModel‘s getColumnClass(int columnIndex) must return the type of data stored in a cell. When it returns that the column stored a Boolean data, JTable displays a checkbox as the default renderer or editor for that cell.

package org.kodejava.swing;

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

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

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

        JFrame frame = new JFrame("JTable Boolean as Checkbox");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

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

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

        JTable table = new JTable(new BooleanTableModel());
        table.setFillsViewportHeight(true);
        JScrollPane pane = new JScrollPane(table);
        add(pane, BorderLayout.CENTER);
    }

    static class BooleanTableModel extends AbstractTableModel {
        String[] columns = {"STUDENT ID", "NAME", "SCORE", "PASSED"};
        Object[][] data = {
                {"S001", "ALICE", 90.00, Boolean.TRUE},
                {"S002", "BOB", 45.50, Boolean.FALSE},
                {"S003", "CAROL", 60.00, Boolean.FALSE},
                {"S004", "MALLORY", 75.80, Boolean.TRUE}
        };

        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 checkbox. A
        // number value is right aligned.
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return data[0][columnIndex].getClass();
        }
    }
}

Here is the result of the program:

JTable render Boolean as Checkbox

JTable render Boolean as Checkbox

Wayan

1 Comments

Leave a Reply

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