Java - JTable - setting cell to prevent editing

I have a JTable with a model created as:

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

      

Where arrays are created. However, for now, you can edit the cells. How can I prevent this?

Thank!

+3


source to share


2 answers


Extend the JTable or DefaultTableModel, override the method isCellEditable(int row, int column)

and return false for cells that you don't want the user to edit.

For example, if you don't want the user to be able to modify the second column, you would do something like:

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

      

Please note that the above method can be compressed and rewritten 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, just try this method to always return false:

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

      

+5


source


Subclass or create anonymous version DefaultTableModel

and override the method isCellEditable

.



+2


source







All Articles