如何在Java中使JTable可编辑

8
我在Java中使用JTable,但它不允许我编辑单元格。
private final TableModel dataModel = new AbstractTableModel() {

        public int getColumnCount() { 
            return 5; 
        }

        public int getRowCount() { 
            return 10;
        }

        public Object getValueAt(int row, int col) { 
            return new Integer(row*col); 
        }
};

private final JTable table = new JTable(dataModel);

3
请确保花时间阅读如何使用表格 - MadProgrammer
4个回答

12

添加以下代码

 public boolean isCellEditable(int row, int col)
      { return true; }
 public void setValueAt(Object value, int row, int col) {
    rowData[row][col] = value;
    fireTableCellUpdated(row, col);
  }

你应该有一个数组来保存更改


3

尝试

 private final TableModel dataModel = new AbstractTableModel() {

        public int getColumnCount() { 
            return 5; 
        }

        public int getRowCount() { 
            return 10;
        }

        public Object getValueAt(int row, int col) { 
            return new Integer(row*col); 
        }

        public boolean isCellEditable(int row, int col) {
                    return true;
                }
};

2
在匿名内部类AbstractTableModel中添加isCellEditable()函数。
public boolean isCellEditable(int row, int col) { 
    return true; 
}

0

在你想要可编辑的行和列中添加isCellEditable(),例如,如果你不想让一些列(如ID)可编辑,则返回false。请记住,你需要将编辑后的数据保存在某个地方。

  public boolean isCellEditable(int row, int col) { 
       return true;  // or false for none editable columns
    }
 public void setValueAt(Object value, int row, int col) {
  rowData[row][col] = value; // save edits some where
  fireTableCellUpdated(row, col); // informe any object about changes
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接