Search code examples
javaarraysswingjtabledefaulttablemodel

Java - JTable - Set a cell to not allow editing


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!


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;
        }
    };