JCheckBox
is a component that can be considered "Boolean", that is, is either marked, or is not. Because it has only two states, when you define a column of this type in DefaultTableModel
, the renderer itself uses this component as a representation of a Boolean column , and its only job is to define which column should be of this type. See the example below:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class JTableCheckboxTest extends JFrame{
public void createAndShowGUI() {
Object[][] rowData = {null, null, null};
Object[] columnNames = { "Currency Column ", "Column Two",};
DefaultTableModel model = new DefaultTableModel(rowData, columnNames){
@Override
public Class<?> getColumnClass(int columnIndex) {
return columnIndex == 0 ? Boolean.class : super.getColumnClass(columnIndex);
}
};
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER);
setPreferredSize(new Dimension(300, 150));
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String args[]) throws IllegalAccessException {
EventQueue.invokeLater(() -> new JTableCheckboxTest().createAndShowGUI());
}
}
Notice that in the getColumnClass()
method I check to see if the column index is 0, when it does, the column will be a Boolean type, which will make it a Checkboxes column:
One point of your code is that, by default, all columns of a DefaultTableModel
are editable, so overwriting the isCellEditable()
method to return true is redundant.