how to add a mouse listener to a JTable's cell holding a Boolean value rendered as checkbox

Heisenbug picture Heisenbug · Jun 7, 2011 · Viewed 9.2k times · Source

I have a JTable with a custom model implemented extending AbstractTableModel.

public abstract class AbstractTable extends AbstractTableModel{

     public Class<? extends Object> getColumnClass(int c) {}
}

Because I've implemented the getColumnClass method, Boolean values are rendered in the table like checkboxes. I would like to intercept checkbox's change of status but unfortunately I can't add directly a mouse listener, because I don't have a reference to the checkbox itself, which it isn't created by me.

How can I set a mouse listener to intercept the checkbox status change event?

EDIT:

@jzd answer is correct. I can catch the change in setValue method. But I would like to know how to implement a mouse listener based approach.

Answer

trashgod picture trashgod · Jun 8, 2011

Particularly, I would like to avoid putting the logic inside setValue().

In this example of selectable values, the setValue() method is not overridden, except to update the internal data structure and fire the appropriate event. ValueEditor extends AbstractCellEditor and implements ItemListener, while ValueRenderer extends JCheckBox. In this way the editor can listen to the renderer's JCheckBox inside the editor's itemStateChanged().

Addendum: Adding a CellEditorListener is another approach, shown here for JTree. Note that JTable itself is a CellEditorListener.