Making JTable cells uneditable

后端 未结 4 580
独厮守ぢ
独厮守ぢ 2020-12-19 23:25

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

4条回答
  •  孤城傲影
    2020-12-20 00:11

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

提交回复
热议问题