Reputation: 14751
How can I put a JCheckbox
or a JButton
on a specific row and column of a JTable
?
Upvotes: 1
Views: 8066
Reputation: 324128
As you can tell from khachik's answer support for a check box is provided by a table based on the column class of the column.
However, if you only want a check box on a specific row of a specific column then you need to override the getCellRenderer(...) and getCellEditor(...) methods to return the renderer/editor for the given cell. Something like:
public TableCellEditor getCellEditor(int row, int column)
{
int modelColumn = convertColumnIndexToModel( column );
if (modelColumn == 1 && row < 3)
return getDefaultEditor(Boolean.class);
else
return super.getCellEditor(row, column);
}
Upvotes: 1
Reputation: 10519
For that, you'll have to write a TableCellRenderer
and a TableCellEditor
.
You can derive from default swing implementations to make it easier.
In each class, you'll have to override the one method of these interfaces, and in it, check the passed row
and column
arguments; if both row and column match your criteria, then return a JCheckBox
or a JButton
, otherwise return the JComponent
returned by the super
implementation (when using default swing implementations of these interfaces).
Upvotes: 0
Reputation: 28693
Not sure about a button, but here is a working example to put a checkbox:
import javax.swing.*;
import javax.swing.table.*;
public class Test {
public static void main(String [] args) throws Exception {
DefaultTableModel model = new DefaultTableModel(null, new String [] {"CheckMe", "Value"}) {
public Class getColumnClass(int c) {
switch (c) {
case 0: return Boolean.class;
default: return String.class;
}
} };
JTable table = new JTable(model);
JFrame frame = new JFrame("CheckBox Test");
frame.add(table);
model.addRow(new Object [] {true, "This is true"});
model.addRow(new Object [] {false, "This is false"});
frame.pack(); frame.validate();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Upvotes: 2