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 ch开发者_运维知识库ecked 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.
精彩评论