Reputation: 43
I named my JTable tblList and I wanted a certain column to be not-editable. I have found the below code that should do the job however, i cannot for the life of me make it work on my existing table. I guess my question in particular is, how do I call the below codes to be set on my existing table named tblList?
JTable model = new JTable(){
@Override
public boolean isCellEditable(int row, int column){
return column==3 false;
};
};
Upvotes: 0
Views: 1250
Reputation: 5403
The way of doing this would be to have your own TableModel
and override the public boolean isCellEditable(int rowIndex, int columnIndex);
. As a rule of thumb, we should not override a JTable
method. For your reference, this is what JTable does - delegates the call to the data model:
public boolean isCellEditable(int row, int column) {
return getModel().isCellEditable(convertRowIndexToModel(row),
convertColumnIndexToModel(column));
}
The way we do it is: Step 1: Create a Table model:
public class SimpleTableModel extends DefaultTableModel {
@Override
boolean isCellEditable(int row, int col) {
// Your logic goes here
}
}
Step 2: Pass an instance of this class to the constructor of JTable
JTable table = new JTable (new SimpleTableModel());
Please find a working example below (this is not the way I usually write code and nor should you but just to give you an example):
static class Table extends JFrame {
public Table() {
String[] columns = new String[] {
"Id", "Name", "Hourly Rate", "Part Time"
};
//actual data for the table in a 2d array
Object[][] data = new Object[][] {
{1, "John", 40.0, false },
{2, "Rambo", 70.0, false },
{3, "Zorro", 60.0, true },
};
TableModel m = new AbstractTableModel() {
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];
}
@Override
public int getRowCount() {
return data.length;
}
@Override
public int getColumnCount() {
return data[0].length;
}
@Override
public boolean isCellEditable (int row, int col) {
return false;
}
};
//create table with data
JTable table = new JTable(m);
//add the table to the frame
this.add(new JScrollPane(table));
this.pack();
this.setVisible(true);
}
}
Upvotes: 2