Java - JCheckBox in a JTable cell

 
Now we shall discuss how to include a JCheckBox in a table cell.

CheckBoxJFrame.java
 
/**
 * CheckBoxJFrame.java
 *
 * Created on Aug 2, 2013, 11:57:36 PM
 */

package me.dhanoop.forblog;

import java.awt.Component;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

/**
 *
 * @author dhanoopbhaskar
 */
public class CheckBoxJFrame extends javax.swing.JFrame {

    private JCheckBox tableData = null;
    /** Creates new form CheckBoxJFrame */
    public CheckBoxJFrame() {
        initComponents();
        customizeTable();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // 
    private void initComponents() {

        dbScrollPane = new javax.swing.JScrollPane();
        dbTable = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        dbTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Title 1"
            }
        ));
        dbScrollPane.setViewportView(dbTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(dbScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 226, 
javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(dbScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 81, 
javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// 

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CheckBoxJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JScrollPane dbScrollPane;
    private javax.swing.JTable dbTable;
    // End of variables declaration

    private void customizeTable() {
        Object[] columnNames = new Object[1];
        columnNames[0] = "CheckBox";
        String checkString = "Gate Qualified?";
        Object[][] rowData = new Object[1][1];
        rowData[0][0] = checkString;
        DefaultTableModel tableModel = new DBTableModel(rowData, columnNames);
        dbTable.setModel(tableModel);        
        tableData = new JCheckBox(checkString);
        tableData.setSelected(false);
        tableData.addItemListener(new ItemListener() {

            public void itemStateChanged(ItemEvent e) {
                String result = "";
                if (tableData.isSelected()) {
                    result = "YES";
                } else {
                    result = "NO";
                }
                JOptionPane.showMessageDialog(new JFrame(), result, "Gate Qualified?",
JOptionPane.INFORMATION_MESSAGE);
            }
        });
        
        dbTable.getColumnModel().getColumn(0).setCellEditor(
new DefaultCellEditor(tableData));
        dbTable.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer() {

            public Component getTableCellRendererComponent(JTable table, Object value, 
boolean isSelected, boolean hasFocus, int row, int column) {
                return tableData;
            }
        });
        
        dbTable.updateUI();
    }

}


DBTableModel.java
 
package me.dhanoop.forblog;

import javax.swing.table.DefaultTableModel;

/**
 *
 * @author dhanoopbhaskar
 */
public class DBTableModel extends DefaultTableModel {

    public DBTableModel(Object[] columns) {
        super(columns, 0);
    }

    public DBTableModel(Object[][] data, Object[] columns) {
        super(data, columns);
    }

    @Override
    public boolean isCellEditable(int row, int column) {
        return true;
    }
}

The following is the key snippet in the program. Here we do mainly two things: 
(1) Changing the CellEditor of the ColumnModel of the column at position 0 (zero) of the table
(2) Changing the CellRenderer of the ColumnModel of the column at position 0 (zero) of the table.
 
    private void customizeTable() {
        Object[] columnNames = new Object[1];
        columnNames[0] = "CheckBox";
        String checkString = "Gate Qualified?";
        Object[][] rowData = new Object[1][1];
        rowData[0][0] = checkString;
        DefaultTableModel tableModel = new DBTableModel(rowData, columnNames);
        dbTable.setModel(tableModel);        
        tableData = new JCheckBox(checkString);
        tableData.setSelected(false);
        tableData.addItemListener(new ItemListener() {

            public void itemStateChanged(ItemEvent e) {
                String result = "";
                if (tableData.isSelected()) {
                    result = "YES";
                } else {
                    result = "NO";
                }
                JOptionPane.showMessageDialog(new JFrame(), result, "Gate Qualified?", 
JOptionPane.INFORMATION_MESSAGE);
            }
        });
        
        dbTable.getColumnModel().getColumn(0).setCellEditor(
new DefaultCellEditor(tableData));
        dbTable.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer() {

            public Component getTableCellRendererComponent(JTable table, Object value, 
boolean isSelected, boolean hasFocus, int row, int column) {
                return tableData;
            }
        });
        
        dbTable.updateUI();
    }






Post a Comment

2 Comments

  1. Hi,
    very interesting example thanks!!!
    Do you think would be possible to update this code allowing a Jtable with more rows and columns and a checkbox in each table cell?

    Thanks in advances

    ReplyDelete
    Replies
    1. Hi Rossella Rispoli,
      It is possible to do so. We can place not only check box but also most of the components including combo box, button, radio button, etc in the table cell.

      Delete