I want to make my JTable Non-editable
As I use following code to set rows using SetModel():
jTable1.setModel(DbUtils.resultSetToTableModel(rs)); //Resultset is added as each row using r2xml JAR file
I cant use follwing code:
jTable1.setModel(new DefaultTableModel() {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
});
Because we cannot use two setModel() for jTable.
How to overcome this problem? I want to setresult and make jTable Noneditable.
Here are 2 ways to achieve that:
Create and use your own TableModel
implementation which forwards all calls to the table model returned by DbUtils
except for isCellEditable()
in which you can return always false
hence disabling editing. Your own table model could get the model returned by DbUtils
as a constructor argument for example.
You can extend JTable
and override its isCellEditable()
method to return false
(by default it calls the model's isCellEditable()
method). Maybe other Swing enthusiasts will see this as an evil hack, but it is the simplest solution to your problem here.
This is how you can create your model:
class MyModel implements TableModel {
private final TableModel m;
public MyModel(TableModel m) {
this.m = m;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
// This is how we disable editing:
return false;
}
// The rest of the methods just forward to the other model:
@Override
public int getRowCount() {
return m.getRowCount();
}
@Override
public int getColumnCount() {
return m.getColumnCount();
}
// ...and all other methods which I omit here...
}
And this is how you can use it:
jTable1.setModel(new MyModel(DbUtils.resultSetToTableModel(rs)));
Extending JTable
can even be an anonymous class:
JTable jtable1 = new JTable() {
@Override
public boolean isCellEditable(int row, int column) {
// This is how we disable editing:
return false;
}
};
And using it:
// You can set any model, the table will not be editable because we overrode
// JTable.isCellEditable() to return false therefore the model will not be asked
// if editable.
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
您只需在程序jTable.disable()中编写一行,就可以使用此代码来使jTable不可编辑。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.