I have a Jtable in which I want to add a JCheckbox in one column. However, when I create a JCheckbox object, javax.swing.JCheckBox is being displayed in the column.Please refer to the image. Can you tell me how to amend that please? I have searched everywhere but cannot seem to find any solution for it. Thank you.
Asked
Active
Viewed 3,194 times
1 Answers
4
- don't add components to your
TableModel
, that's not the responsibility of theTableModel
- You will need to specify the class type of your column. Assuming you're using a
DefaultTableModel
, you can simply fill the column with a bunch of booleans and this should work - After testing, you will need to override thegetColumnClass
method of theDefaultTableModel
(or what everTableModel
implementation) and make sure that for the "check box" column, it returnsBoolean.class
See How to use tables for more details
For example...
import java.awt.EventQueue;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class TestCardLayout {
public static void main(String[] args) {
new TestCardLayout();
}
public TestCardLayout() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
Random rnd = new Random();
DefaultTableModel model = new DefaultTableModel(new Object[]{"Check boxes"}, 0) {
@Override
public Class<?> getColumnClass(int columnIndex) {
return Boolean.class;
}
};
for (int index = 0; index < 10; index++) {
model.addRow(new Object[]{rnd.nextBoolean()});
}
JTable table = new JTable(model);
final JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

MadProgrammer
- 343,457
- 22
- 230
- 366
-
I am not using any table model just the default one. I have used vectors to construct the table. I have also tried Booleans but true and false are being displayed, not the JCheckBox. Thanks – user3419642 May 23 '14 at 06:37
-
1- You are using a `TableModel`, it just happens to be called `DefaultTableModel`, which has a method called `getColumnClass` which you need to override in order to return the expected class type for each column and make sure, for the check box column, you return `Boolean.class`, as the example demonstrates, then all the magic happens for you – MadProgrammer May 23 '14 at 06:43
-
Do you need a new DefaultTableModel for each column? How would you scale this to hold the whole table? – bmc Jul 31 '18 at 13:43
-
1@bmc No, you only need one TableModel – MadProgrammer Jul 31 '18 at 19:38