views:

25

answers:

2

I've searched for this for quite a while and haven't found a clear example anywhere. I'm a Java newbee using NetBeans. I have a boolean value in the first column of a JTable (called "Enabled") and I have some plugin code that I need to call to see if it has the settings it needs in order to be enabled, and if not, display a message box and prevent Enabled from being checked.

All I really need is for a function to be called when the checkbox is checked and I can take it from there. Does anyone have an example of how to do this?

Thanks for your help!

Harry

+1  A: 

You probably want a TableModelListener, as discussed in Listening for Data Changes. Alternatively, you can use a custom editor, as discussed in Concepts: Editors and Renderers and the following section.

trashgod
+1, the TableModelListener is the way to go when you want to know when a value in the model has been changed.
camickr
Ah, that's the stuff! Thanks for your help! Now I just have to clean up from all my failed attempts that didn't work!
Harry Strand
+1  A: 

All I really need is for a function to be called when the checkbox is checked

When the checkbox is checked then the value will be changed in the model, which is probably not what your want. I would think you want to prevent the checking of the checkbox in the first place.

The way to prevent a cell from being editable is to override the isCellEditable(...) method of JTable. By overriding this method you can dynamically determine if the cell should be editable or not.

JTable table = new JTable( ... )
{
    public boolean isCellEditable(int row, int column)
    {
        int modelColumn = convertColumnIndexToModel( column );

        if (modelColumn == yourBooleanColumn)
            return isTheBooleanForThisRowEditable(row);
        else
            return super.isCellEditable(row, column);
    }
};

And a fancier approach would be to create a custom renderer so that the check box looks "disabled" even before the user attempts to click on the cell. See the link provided by trashgod on renderers.

camickr
+1 for demonstrating the required index transformation. An added benefit of the custom renderer is being able to specify a tool tip.
trashgod