dynamic JTable and rendering column as JComboBox
843805Aug 9 2006 — edited Aug 10 2006I originally posted this to the "Java Programming" topic, but it was suggested that I move it over here.
I'm new to cell renderers and editors, so I'm hoping someone can put me on the right path.
I've got a JTable that is initially empty. I've set one column to use a custom cell renderer that extends JComboBox and implements TableCellRenderer.
The user can add rows to the table at any time, I'm using TableModel.addRow() for this. When I call addRow, I pass the entryies for the JComboBox column as a String[], with one array element for each entry in the JComboBox.
In my custom renderer, I take the values from the array and use JComboBox.addItem() to add them to the JComboBox.
When I run the code, it appears fine, but the JComboBox doesn't function, i.e. it is not editable (yes, the column is set as editable). I assume I need to add a custom editor. I tried
table.setCellEditor(new DefaultCellEditor(ComboBoxCellRenderer);
and the combobox was now editable, but it was empty and I got nullpointer exceptions.
What am I missing?
Any help is appreciated. Here is what I'm trying:
**************** Constructing the table **************
DefaultTableModel tablemodel = new DefaultTableModel(columnnames,0);
datasourcestable = new JTable(tablemodel) ;
// Set custom renderer for particular columns in this JTable
ComboBoxCellRenderer renderer = new ComboBoxCellRenderer();
TableColumn waveformscalarcolumn = datasourcestable.getColumnModel().getColumn(datasourcestable.getColumn("Title").getModelIndex());
waveformscalarcolumn.setCellRenderer(renderer);
// tried the following, combobox becomes editable but empty
//waveformscalarcolumn.setCellEditor(new DefaultCellEditor(renderer));
*************** Adding rows to the table (Event Code)*********************
DefaultTableModel tablemodel = (DefaultTableModel)datasourcestable.getModel();
Object[] rowdata = new Object[3];
rowdata[0] = "gaga";
String[] cboxentries = {"cbox entry 1","cbox entry 2"};
rowdata[1] = cboxentries;
rowdata[1] = "gaga"'
tablemodel.addRow(rowdata);
**************** Custom Cell Renderer **********************
class ComboBoxCellRenderer extends JComboBox implements TableCellRenderer {
public ComboBoxCellRenderer() {
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected, boolean hasFocus, int row, int column) {
String[] stringarray = (String[]) value;
for (int i=0; i<stringarray.length; i++){
this.addItem(stringarray);
}
return this;
}
}