How do I make a JTable editable in java

元气小坏坏 提交于 2019-12-23 09:57:13

问题


I'm using a JTable in java, but it won't let me edit the cells.

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

回答1:


add the follwoing code

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

you should have a array where you will save the changes




回答2:


Add isCellEditable() function inside the anonymous inner class AbstractTableModel

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



回答3:


Try

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



回答4:


Add isCellEditable() to the rows and columns you want them to be editable, example if you don't want some columns like ID to be editable return false. Keep in mind that you need to save the editit data some where

  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
}


来源:https://stackoverflow.com/questions/16008145/how-do-i-make-a-jtable-editable-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!