使JTable单元不可编辑

编程入门 行业动态 更新时间:2024-10-23 09:26:37
本文介绍了使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单元不可编辑

本文发布于:2023-11-23 01:24:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619607.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元   编辑   JTable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!