I need to put JComboBox
into JTable
. The JComboBox
should contain a list of entries corresponding to particular row. For instance:
Position | Skills
Programmer | List<String{Java,C,C++}
Web Programmer | List<String{javaScript,PHP,MySQL}
I populate the table with Object[][] data
. One of columns of data
contains List<String>
.
I wrote the following renderer. However, the problem is that it outputs the content of JComboBox
in each row is the same.
DefaultTableCellRenderer cellRenderer = new DefaultTableCellRenderer()
{
public Component getTableCellRendererComponent( JTable table, Object value, boolean
isSelected, boolean hasFocus, int row, int column)
{
super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column );
if ( value instanceof List<?>)
{
int vColIndex = 5;
TableColumn col = table.getColumnModel().getColumn(vColIndex);
col.setCellEditor(new ComboBoxEditor(((ArrayList<?>) value).toArray()));
col.setCellRenderer(new ComboBoxRenderer(((ArrayList<?>) value).toArray()));
}
return this;
}
};
table = new JTable(model);
for (int i = 0; i < table.getColumnCount(); ++i)
{
table.getColumnModel().getColumn(i).setCellRenderer(cellRenderer);
}
ComboBox renderers:
class ComboBoxRenderer extends JComboBox implements TableCellRenderer {
public ComboBoxRenderer(Object[] objects) {
super(objects);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
// Select the current value
setSelectedItem(value);
return this;
}
}
class ComboBoxEditor extends DefaultCellEditor {
public ComboBoxEditor(Object[] objects) {
super(new JComboBox(objects));
}
}
JComboBox box=new JComboBox(values);
TableColumn col = table.getColumnModel().getColumn(0);
col.setCellEditor(new DefaultCellEditor(box));