Question

I have a custom TableCellRenderer (ValueRenderer) for a JTable, the cell is a Checkbox.

I have attached an ItemListener to the valueRenderer to listen to the checkbox's state change (selected/deselected) as mentioned by this example.

My problem is that inside the itemStateChanged(ItemEvent e), I do not know how to get the row in which this checkbox is contained knowing that the ItemEvent source is the ValueRenderer.

Can you help me?

Here is some of my code:

Custom TableCellRender:

public class ValueRenderer extends JCheckBox implements TableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
        this.setSelected((Boolean) value);
        return this;
    }

} 

ItemListener:

public class TableRowCheckBoxListener implements ItemListener {

    private JTable hqlRequestTable;

    public TableRowCheckBoxListener(JTable hqlRequestTable) {
        this.hqlRequestTable = hqlRequestTable;
    }

    @Override
    public void itemStateChanged(ItemEvent e) {

        /*How do I get the row which contains the checkbox clicked knowing that :
            e.getSource() == ValueRenderer
            e.getItem() == ValueRender
        */
    }

}
Was it helpful?

Solution

If you want to know when some value changes in your table, you must not register a listener on the renderer. You must register a listener on the table model: that's where the data displayed by the table is held, and that's the object which fires an event if anything changes in the data.

The alternative is to use a custom table model consisting in a list of beans, have the table model modify the properties of the beans it holds, and have the bean fire a property change event when a property changes. You'll then register listeners on the beans themselves rather than registering a table model listener (note that the table model still has to fire table model events, though).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top