Amre
Amre

Reputation: 1680

How do I make a JTable editable in java

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

Upvotes: 8

Views: 27650

Answers (4)

user2286223
user2286223

Reputation:

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
}

Upvotes: 0

Nidhish Krishnan
Nidhish Krishnan

Reputation: 20751

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

Upvotes: 3

Mohan Raj B
Mohan Raj B

Reputation: 1026

Add isCellEditable() function inside the anonymous inner class AbstractTableModel

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

Upvotes: 2

aymankoo
aymankoo

Reputation: 671

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

Upvotes: 12

Related Questions