我需要将JComboBox
放入JTable
。 JComboBox
应包含与特定行对应的条目列表。例如:
Position | Skills
Programmer | List<String{Java,C,C++}
Web Programmer | List<String{javaScript,PHP,MySQL}
我用Object[][] data
填充表格。其中一列data
包含List<String>
。
我写了以下渲染器。但问题是它输出的每行中JComboBox
的内容是相同的。
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渲染器:
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));
}
}
答案 0 :(得分:0)
JComboBox box=new JComboBox(values);
TableColumn col = table.getColumnModel().getColumn(0);
col.setCellEditor(new DefaultCellEditor(box));