Making JTable cells uneditable

codeMasterFiveThousand picture codeMasterFiveThousand · Dec 4, 2011 · Viewed 9.8k times · Source

I am trying to make all the cells of a JTable uneditable when double clicked by the user. I have read a lot of forum posts and the general consensus is to create a new table model class, extend DefaultTableModel and then override method isCellEditable(int row, int column). I did all of this and now when I run my program (applet) Nothing shows up in the cells. NOTE I have a prof this semester that does not think applets are outdated...

Code for the table model:

public class MyTableModel extends DefaultTableModel
{
    public boolean isCellEditable(int row, int column)      //override isCellEditable
    //PRE:  row > 0, column > 0
    //POST: FCTVAL == false always
    {
        return false;
    }
}

    Code in my class:  **NOTE** this class extends JPanel 

    private JScrollPane storesPane;                
    private JTable storesTable; 

    Code in the Constructor:             

    storesTable = new JTable(tableData, COL_NAMES);    //tableData and COL_NAMES are passed in
    storesTable.setModel(new MyTableModel());

    storesPane = new JScrollPane(storesTable);
    storesTable.setFillsViewportHeight(true);
    add(storesPane, BorderLayout.CENTER);     

Hopefully some of you Java Gurus can find my error :)

Answer

Hovercraft Full Of Eels picture Hovercraft Full Of Eels · Dec 4, 2011

This line creates a new JTable and implicitly creates a DefaultTableModel behind the scenes, one that holds all the correct data needed for the JTable:

storesTable = new JTable(tableData, COL_NAMES);

And this line effectively removes the table model created implicitly above, the one that holds all of the table's data and replaces it with a table model that holds no data whatsoever:

storesTable.setModel(new MyTableModel());

You need to give your MyTableModel class a constructor and in that constructor call the super constructor and pass in the data that you're currently passing to the table in its constructor.

e.g.,

public class MyTableModel extends DefaultTableModel {

   public MyTableModel(Object[][] tableData, Object[] colNames) {
      super(tableData, colNames);
   }

   public boolean isCellEditable(int row, int column) {
      return false;
   }
}

Then you can use it like so:

MyTableModel model = new MyTableModel(tableData, COL_NAMES);
storesTable = new JTable(model);