简体   繁体   中英

Notification when a checkbox in a JTable is checked

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM