结合使用JTable和JComboBox

时间:2013-03-06 10:15:47

标签: java swing jtable jcombobox

我正在尝试创建一个JTable,它在一个单元格中有一个JComboBox。我知道我可以使用celleditor,但诀窍是我想在每一行的组合框中提供不同的信息。表中的每一行代表一个对象,在该对象上有一个arraylist,它是我在组合框中想要的那个arraylist的内容。到目前为止,这是我的思考过程。

table = new JTable(tableModel);
tableModel = new DefaultTableModel();
forestTable.setModel(tableModelForest);
tmpColum = forestTable.getColumnModel().getColumn(5);
tmpColum.setCellEditor(new DefaultCellEditor(comboBox));
comboBox = new JComboBox<Tree> ();
comboBox.setEditable(false);

现在,当我稍后调用该方法时(通过按下按钮),我想在coloum 5中插入一个带有独特组合框的新行,但我不知道它是怎么做的。我试过了。

public void fillTable(String text){
    tableModel.insertRow(tableModel.getRowCount(), "" } );
    tableModel.fireTableRowsInserted(
    tableModel.getRowCount(),
    tableModel.getRowCount());

    comboBox.addItem(text);

}

1 个答案:

答案 0 :(得分:2)

仍然适当的方法是使用单元格编辑器。

tmpColum.setCellEditor(new DefaultCellEditor(comboBox) {
    @Override
    public Component getTableCellEditorComponent(JTable table,
                                         Object value,
                                         boolean isSelected,
                                         int row,
                                         int column) {
        JComboBox comboBox = (JComboBox)super.getTableCellEditorComponent(
            table, value, isSelected, row, column);
        // stuff the combobox with values and selection.
        ComboBoxModel cbmodel = getMyCBModel(row); // Or (ComboBoxModel)value
        comboBox.setModel(cbmodel);
        // Or:
        if (value == null)
            comboBox.setSelectedIndex(-1);
        else
            comboBox.setSelectedItem(value);
        return comboBox;
    }
});
相关问题