Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

java - Making JTable cells uneditable

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...