2013-04-15 77 views
4

我在java中使用了JTable,但它不會讓我編輯單元格。如何在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

確保你花時間通過[如何使用表(http://docs.oracle.com/javase/tutorial/uiswing閱讀/components/table.html) – MadProgrammer

回答

7

添加follwoing代碼

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); 
    } 

你應該有一個數組,你可以將更改保存

1

添加匿名內部類AbstractTableModel

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

嘗試內isCellEditable()功能

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; 
       } 
}; 
0

將isCellEditable()添加到希望它們可編輯的行和列中,例如,如果不希望某些列如ID可編輯,則返回false。請記住,你需要一些保存editit數據,其中

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 
}