I want to add a combo box as cell editor to my JTable. To achieve this I have used the column.setCellEditor method as follows. But I found that it wasn’t working. How can I fix this?
def treeModel = new GrvTableModel()
table = new JTable( treeModel)
TableColumn col = table.getColumnModel().getColumn(1);
JComboBox com = new JComboBox();
com.addItem("one");
com.addItem("two");
com.addItem("three");
col.setCellEditor (new DefaultCellEditor(com));
.......................
class GrvTableModel extends AbstractTableModel {
public String[] columnNames = [ "key" , "value"]
public Object[][] data = []
public selectedObjArray
//Returns the number of columns in the datamodel
public int getColumnCount() {
return columnNames.length;
}
//Returns the number of rows in the datamodel
public int getRowCount() {
return data.length;
}
//Returns the name of column in the datamodel at the specified index
public String getColumnName(int col) {
return columnNames[col];
}
//Returns the object at the specified [row,column] index
public Object getValueAt(int row, int col) {
return data[row][col];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col == 1) {
return true;
} else {
return false;
}
}
//sets the object at the row and column as specified
public void setValueAt(Object value, int row, int col) {
println "change table row: " + row
data[row][col] = value;
fireTableCellUpdated(row, col);
selectedObjArray[row].val = value
}
}
PS: The table data is added dynamically within an action performed method.
This seems to work (I had to make up test data as you didn’t supply a runnable example)