我想知道如何使 JTable 中的一列可编辑,而其他列则不可编辑。
我已经重写了 isCellEditable() 方法,但这会将每个单元格都设置为不可编辑。提前感谢您的回答。
你可以为TableColumn
或者TableColumn和TableCell
设置isEditable
属性。
@Override
public boolean isCellEditable(int row, int col) {
switch (col) {
case 0:
case 1:
return true;
default:
return false;
}
}
覆盖 表模型
isCellEditable(int rowIndex, int columnIndex)
接受两个参数,只需为您想要的列返回 true 即可?
public boolean isCellEditable(int rowIndex, int columnIndex){
return columnIndex == 0; //Or whatever column index you want to be editable
}
columnIndex == 0
而不是 rowIndex == 0
。 - Eng.Fouad这将使第3列和第8列的“editable”属性为true,其他列的属性为false。
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];
}
};
SwingX项目的JXTable / TableColumnExt具有每个表和每个列配置可编辑性的API。
// make the table completely read-only
xTable.setEditable(false);
// make a column read-only
xTable.getColumnExt(index).setEditable(false);
你也可以创建一个继承JTable
的类,并添加一个布尔数组。
public class MyTable extends JTable {
private Boolean[] editable_columns;
public DetailsTable(Object[][] rowData, Object[] columnNames) {
super(rowData, columnNames);
editable_columns = new Boolean[columnNames.length];
for (int i = 0; i < columnNames.length; i++){
editable_columns[i] = true;
}
}
public void setColumnEditable(int index, boolean isEditable){
if (index > -1 && index < editable_columns.length){
editable_columns[index] = isEditable;
}
}
在覆盖setValueAt
方法之后,使用您的布尔数组
@Override
public void setValueAt(Object aValue, int row, int column) {
if (editable_columns[column])
super.setValueAt(aValue, row, column);
}
阅读Kleopatra的评论(他第二次建议看一下javax.swing.JXTable,现在我很抱歉我第一次没有看)我建议你跟随这个链接
我搜索了答案,并将几个答案结合起来得到了自己的解决方案:(然而,并非所有解决方案都安全,但易于理解和快速实现,尽管我建议您查看上面的链接)
您可以使其更灵活,以便稍后设置哪些列可编辑或不可编辑,例如我使用了以下代码:
columnsEditable=new ArrayList<Integer>();
table=new JTable(new DefaultTableModel(){
@Override
public boolean isCellEditable(int row, int col) {
if(columnsEditable.isEmpty()){
return false;
}
if(columnsEditable.contains(new Integer(col))){
return true;
}
return false;
}
});
我使用了这个函数来设置是否可编辑:
public void setColumnEditable(int columnIndex,boolean editable){
if(editable){
if(!columnsEditable.contains(new Integer(columnIndex))){
columnsEditable.add(new Integer(columnIndex));
}
}else{
if(columnsEditable.contains(new Integer(columnIndex))){
columnsEditable.remove(new Integer(columnIndex));
}
}
}
private JTable table;
private ArrayList<Integer> columnsEditable;