如何使JTable单元动态地可编辑/不可编辑?

问题描述:

有什么方法可以在jtable中动态制作不可编辑的单元格吗?每当用户提供类似false的输入时,我都想创建不可编辑的单元格...我已经在DefaultTableModel isCellEditable方法中看到过.有人可以帮助我吗?.谢谢

Is there any way to make non editable cell dynamically in 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. 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);
    }
}

其他班级

... stuff
DefaultTableModel myModel = new MyDefaultTableModel(x, y); 
table.setModel(myModel);
... stuff

然后您可以使用已存储的myModel变量并在理论上调用setCellEditable()函数来动态设置值.我尚未测试此代码,但它应该可以工作.您可能仍然需要触发某种事件来触发表格以注意到更改.

You can then set the values dynamically by using the myModel variable you have stored and calling the setCellEditable() function on it.. in theory. 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.