如何将JComboBox放入JTable以显示每行的List <string> </string>

时间:2014-03-20 17:39:15

标签: java swing jtable jcombobox tablecellrenderer

我需要将JComboBox放入JTableJComboBox应包含与特定行对应的条目列表。例如:

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

1 个答案:

答案 0 :(得分:0)

    JComboBox box=new JComboBox(values);
    TableColumn col = table.getColumnModel().getColumn(0);
    col.setCellEditor(new DefaultCellEditor(box));