DefaultTableModel make cell not editable JTable

Dave picture Dave · Oct 11, 2012 · Viewed 17.2k times · Source

I have an JAVA project and want to make my JTable with a DefaultTableModel non-editable. I know a work-around to do this, called:

JTable table = new JTable(...){  
  public boolean isCellEditable(int row, int column){  
    return false;  
  }  
};  

Like said: i dont like this. This is not according the rules of my school training.

Is there any way to do this? Maybe is there a good way. I hope so!

Answer

JB Nizet picture JB Nizet · Oct 11, 2012

You should not subclass the JTable itself, but the table model:

DefaultTableModel myModel = new DefaultTableModel(...) {
    @Override
    public boolean isCellEditable(int row, int column) {
        return false;
    }
}

Or even better, don't use a DefaultTableModel, and use an AbstractTableModel that directly gets the information in your business objects rather than copying all the information from the business objects to Vectors.