Question

I have a JTable with a model instantiated as:

TableModel ss = new DefaultTableModel(myArray[][], myHeaderArray[]);

Where the arrays are generated. However, at the moment, you can still edit cells. How can I prevent this?

Thanks!

Was it helpful?

Solution

Extend JTable or the DefaultTableModel, override the isCellEditable(int row, int column) method, and return false for the cells that you don't want the user to be able to edit.

For instance, if you didn't want the user to be able to modify the 2nd column, then you'd do something like:

@Override
public boolean isCellEditable(int row, int column) {
   if (column == 1) {
      return false;
   }  else {
      return true;
   }
}

Note as per mre's comment that the above method could be compressed and re-written as:

@Override
public boolean isCellEditable(int row, int column) {
   return (column != 1);
}

If you don't want the user to be able to edit any cells, then simply have this method return false always:

// anonymous inner class example
TableModel ss = new DefaultTableModel(myArray[][], myHeaderArray[]) {
    @Override
    public boolean isCellEditable(int row, int column) {
       return false;
    }
};

OTHER TIPS

Subclass or create an anonymous version of DefaultTableModel and override the isCellEditable method.

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