Vivek
Vivek

Reputation: 1461

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....', how do I get it to show a checkbox and add actions to it?

Upvotes: 3

Views: 8463

Answers (5)

Pav
Pav

Reputation: 21

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 :)

Upvotes: 2

camickr
camickr

Reputation: 324197

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
        }
    }
}

Upvotes: 2

Pokuri
Pokuri

Reputation: 3082

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

Upvotes: 0

Uhlen
Uhlen

Reputation: 1778

JTable have default checkbox renderer/editor for boolean values. Just make your TableModel#getColumnClass return Boolean.class for given column.

Upvotes: 4

hvgotcodes
hvgotcodes

Reputation: 120308

You could use a custom table cell renderer.

See here

http://www.exampledepot.com/egs/javax.swing.table/CustRend.html

Upvotes: 0

Related Questions