How to make JTable cell editable/noneditable dynamically?

走远了吗. 提交于 2019-12-30 08:20:08

问题


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


回答1:


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




回答2:


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

Then I declared editable as a private boolean that can be set e.g.:

    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.



来源:https://stackoverflow.com/questions/12776021/how-to-make-jtable-cell-editable-noneditable-dynamically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!