使JTable单元不可编辑 [英] Making JTable cells uneditable

查看:93
本文介绍了使JTable单元不可编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在用户双击时使JTable的所有单元格都不可编辑。我已经阅读了很多论坛帖子,一般的共识是创建一个新的表模型类,扩展DefaultTableModel然后重写方法isCellEditable(int row,int column)。我做了所有这些,现在当我运行我的程序(applet)时,没有任何东西出现在单元格中。 注意我这个学期的教授不认为applet已经过时...

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...

表格模型的代码:

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

希望你们中的一些Java专家可以找到我的错误:)

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

推荐答案

这一行创建一个新的JTable并在幕后隐式创建一个DefaultTableModel,它保存了JTable所需的所有正确数据:

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

您需要为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.

例如,

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

这篇关于使JTable单元不可编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆