Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JTable - Make only one column editable

Tags:

java

swing

jtable

I was wondering how to make one column of a JTable editable, the other columns have to be non editable.

I have overwritten isCellEditable() but this changes every cell to non editable. Thnx in advance.

like image 247
user842479 Avatar asked Nov 17 '11 12:11

user842479


4 Answers

you can set if is isEditable for TableColumn or TableColumn and TableCell too

@Override
public boolean isCellEditable(int row, int col) {
     switch (col) {
         case 0:
         case 1:
             return true;
         default:
             return false;
      }
}
like image 68
mKorbel Avatar answered Oct 11 '22 01:10

mKorbel


Override the table model

isCellEditable(int rowIndex, int columnIndex) takes two arguments, just return true for the column you want?

public boolean isCellEditable(int rowIndex, int columnIndex){
return columnIndex == 0; //Or whatever column index you want to be editable
}
like image 32
EricR Avatar answered Oct 11 '22 02:10

EricR


this would set editable true for column 3 and 8 and false for others .

DefaultTableModel model = new DefaultTableModel() {

            boolean[] canEdit = new boolean[]{
                    false, false, true, false, false,false,false, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
};
like image 20
arash Avatar answered Oct 11 '22 00:10

arash


JXTable/TableColumnExt of the SwingX project have api to configure editability per-table and per-column

 // make the table completely read-only
 xTable.setEditable(false);
 // make a column read-only
 xTable.getColumnExt(index).setEditable(false);

Note that it is only possible to narrow the editability compared to that returned by model.isCellEditable. That is you can make a editable cell read-only but not the other way round

like image 31
kleopatra Avatar answered Oct 11 '22 00:10

kleopatra