简体   繁体   English

如何将JComboBox放入JTable中以显示列表 <String> 每行

[英]How to put JComboBox into JTable to show List<String> per row

I need to put JComboBox into JTable . 我需要将JComboBox放入JTable The JComboBox should contain a list of entries corresponding to particular row. JComboBox应该包含对应于特定行的条目列表。 For instance: 例如:

    Position          |   Skills
    Programmer        |   List<String{Java,C,C++}
    Web Programmer    |   List<String{javaScript,PHP,MySQL}

I populate the table with Object[][] data . 我用Object[][] data填充表。 One of columns of data contains List<String> . data列之一包含List<String>

I wrote the following renderer. 我编写了以下渲染器。 However, the problem is that it outputs the content of JComboBox in each row is the same. 但是,问题在于它输出的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 renderers: 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));
    }
}
    JComboBox box=new JComboBox(values);
    TableColumn col = table.getColumnModel().getColumn(0);
    col.setCellEditor(new DefaultCellEditor(box));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM