Adding CheckBox to DefaultTableModel
I have a DefaultTableModel which is populated with an Object[][] array.
Now I want to add a column with checkBoxes and perform operations accordingly.
When I add the checkbox into the Object[][] array and view it, I get text displayed
'javax.swing.JCheckBox[,0,0,0x0....', h开发者_如何学Cow do I get it to show a checkbox and add actions to it?
JTable have default checkbox renderer/editor for boolean values. Just make your TableModel#getColumnClass
return Boolean.class
for given column.
how do I get it to show a checkbox
See Uhlen's answer
and add actions to it?
Use a TableModelListener. Something like:
public void tableChanged(TableModelEvent e)
{
if (e.getType() == TableModelEvent.UPDATE)
{
int row = e.getFirstRow();
int column = e.getColumn();
if (column == ?)
{
TableModel model = (TableModel)e.getSource();
Boolean value = (Boolean)model.getValueAt(row, column));
if (value.booleanValue())
// add your code here
}
}
}
You could also just get the class, instead of hard coding each return type. Here is an example for the override method :
//create the table
DefaultTableModel tableModel = new DefaultTableModel(data, columnNames)
//override the method
{
public Class<?> getColumnClass(int colIndex) {
return getValueAt(0, colIndex).getClass();
}
Then, when you create the table you initialize it this way:
data[i][12] = new Boolean(false);
which makes the box appear unticked :)
You could use a custom table cell renderer.
See here
http://www.exampledepot.com/egs/javax.swing.table/CustRend.html
No you cannot provide swing component as model object[] array. That should be registered as cell editor on column.
Anyway by default DefaultTableModel supports checkbox as editor for columns under which Boolean class type values are stored.
So, in the array pass Boolean.TRUE/Boolean.FALSE object and set table as editable. Then table automatically renders checkbox for you.
Are you need to register editor for each class type
精彩评论