Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make JTable cell editable/noneditable dynamically?

Tags:

java

swing

jtable

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

like image 275
shree Avatar asked Oct 08 '12 05:10

shree


2 Answers

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.

like image 59
calderonmluis Avatar answered Oct 17 '22 01:10

calderonmluis


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.

like image 31
onx Avatar answered Oct 17 '22 01:10

onx