[英]How to make JTable cell editable/noneditable dynamically?
Is there any way to make non editable cell dynamically in jtable ? 有没有办法在jtable中动态制作不可编辑的单元格? Whenever user gives input like false, i want to make non editable cell...I have seen in DefaultTableModel isCellEditable method.But if i want to use that i have create each time new object.So i want to change it non editable dynamically. 每当用户给出像false这样的输入时,我想制作不可编辑的单元格......我在DefaultTableModel中看到了isCellEditable方法。但是如果我想使用我每次创建新对象的时候。所以我想要动态地改变它不可编辑。 Can you anyone please help me?..thanks 你能帮助我吗?谢谢
public class MyDefaultTableModel extends DefaultTableModel {
private boolean[][] editable_cells; // 2d array to represent rows and columns
private MyDefaultTableModel(int rows, int cols) { // constructor
super(rows, cols);
this.editable_cells = new boolean[rows][cols];
}
@Override
public boolean isCellEditable(int row, int column) { // custom isCellEditable function
return this.editable_cells[row][column];
}
public void setCellEditable(int row, int col, boolean value) {
this.editable_cells[row][col] = value; // set cell true/false
this.fireTableCellUpdated(row, col);
}
}
other class 其他课程
... stuff
DefaultTableModel myModel = new MyDefaultTableModel(x, y);
table.setModel(myModel);
... stuff
You can then set the values dynamically by using the myModel variable you have stored and calling the setCellEditable() function on it.. in theory. 然后,您可以使用您存储的myModel变量动态设置值,并在其上调用setCellEditable()函数。理论上。 I have not tested this code but it should work. 我没有测试过这段代码,但它应该可行。 You may still have to fire some sort of event to trigger the table to notice the changes. 您可能仍然需要触发某种事件来触发表以注意更改。
I had similar problems to figure out how to enable/disable editing of a cell dynamically (in my case based on occurences in a database.) I did it like this: 我有类似的问题来弄清楚如何动态地启用/禁用单元格的编辑(在我的情况下基于数据库中的出现。)我这样做:
jTableAssignments = new javax.swing.JTable() {
public boolean isCellEditable(int rowIndex, int colIndex) {
return editable;
}};
That of course overrides isCellEditable. 当然覆盖的是CellEditable。 The only way I could make that work by the way, was to add the declaration to the instantiation of the tabel itself and not the table model. 我可以通过这种方式完成这项工作的唯一方法是将声明添加到tabel本身的实例化而不是表模型。
Then I declared editable as a private boolean that can be set eg: 然后我将editable声明为可以设置的私有布尔值,例如:
private void jTableAssignmentsMouseClicked(java.awt.event.MouseEvent evt) {
if(jTableAssignments.getSelectedRow() == 3 & jTableAssignments.getSelectedColumn() == 3) {
editable = true;
}
else {
editable = false;
}
}
And it works quite well. 而且效果很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.