A JTable is a subclass of JComponent class and it can be used to create a table with information displayed in multiple rows and columns. When a value is selected from a JTable, a TableModelEvent is generated, which is handled by implementing a TableModelListener interface. We can add or insert a checkbox inside a JTable cell by implementing the getColumnClass() method of a Class type.
Example
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class JCheckBoxJTableTest extends JFrame {
private JTable table;
private DefaultTableModel model;
public JCheckBoxJTableTest() {
Random rnd = new Random();
model = new DefaultTableModel(new Object[]{"Check Box1","Check Box2", "Check Box3"}, 0) {
@Override
public Class getColumnClass(int columnIndex) {
return Boolean.class;
}
};
for (int index = 0; index < 10; index++) {
model.addRow(new Object[]{rnd.nextBoolean()});
}
table = new JTable(model);
add(new JScrollPane(table));
setTitle("JCheckBoxJTable Test");
setSize(375, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new JCheckBoxJTableTest();
}
}Output
