views:

376

answers:

2

I am trying to validate a cell in the JTable as soon as the data is entered. I want to make sure that say the correct code is entered in the code column. Could anyone let me know how to do this please?

Thanks

A: 

Add a TableModelListener to the TableModel backing the JTable.

Basically:

myJTable.getModel().addTableModelListener(
  new TableModelListener()
  {
    public void tableChanged(TableModelEvent e)
    {
       //Validate
    }
  }

Alternatively, you could mess around with the cell editor. Look into JTable.setCellEditor and TableCellEditor.

Which would be spiritually equivalent to:

class MyCellEditor extends DefaultTableCellEditor
{
   ...
   public boolean stopEditing()
   {
     return isValid();
   }
}

Note that if you intend to give any visual cues back to the user, things get really hairy with custom TableCellEditors. Just a warning.

Kevin Montrose
How would this work? Presumably the tableChanged callback would only be invoked after the data in the table had changed? ... i.e. This approach couldn't be used to prevent the entry of invalid data.
Adamski
+1  A: 

You should implement a TableCellEditor and perform your validation within the stopCellEditing() method. If validation fails this method should return false. From the Javadoc:

"Tells the editor to stop editing and accept any partially edited value as the value of the editor. The editor returns false if editing was not stopped; this is useful for editors that validate and can not accept invalid entries."

Take a look at the GenericEditor class defined within JTable for an example of this.

One other thing worth looking at: You could always construct a DefaultCellEditor with a JFormattedTextField as a parameter and add an InputVerifier to the text field to prevent entry of invalid data from being committed.

Adamski