简体   繁体   English

结合使用JTable和JComboBox

[英]Combined use of JTable and JComboBox

I'm trying to make a JTable, which has a JComboBox in a cell. 我正在尝试制作一个JTable,它在一个单元格中有一个JComboBox。 I know that i could use a celleditor, but the trick is that i want different information in each row's combobox. 我知道我可以使用celleditor,但诀窍是我想在每一行的组合框中提供不同的信息。 Each row in the table represent an object, on that object are there an arraylist and it's content of that arraylist I want in the comboboxes. 表中的每一行代表一个对象,在该对象上有一个arraylist,它是我在组合框中想要的那个arraylist的内容。 Here's my thought process so far. 到目前为止,这是我的思考过程。

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

Now when i later call the method(by pressing a button), i want to insert a new row with a unique combobox in coloum 5, but i have no idea how do it. 现在当我稍后调用该方法(通过按下按钮)时,我想在coloum 5中插入一个带有独特组合框的新行,但我不知道它是怎么做的。 I've tryed with. 我试过了。

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

    comboBox.addItem(text);

} }

Still the appropiate way is to use a cell editor. 适当的方式仍然是使用单元格编辑器。

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

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

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