0

I'm trying to make a JTable, which has a JComboBox in a cell. I know that i could use a celleditor, but the trick is that i want different information in each row's combobox. 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. 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. I've tryed with.

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

    comboBox.addItem(text);

}

kleopatra
  • 51,061
  • 28
  • 99
  • 211
Simon Nordahl
  • 51
  • 1
  • 8
  • The input is fillTable is string, cause it seemed easier to give an example of string indput instead of arrays – Simon Nordahl Mar 06 '13 at 10:17
  • Use a single `ComboBoxCellEditor`, when `getTableCellEditorComponent` is called, check the row index and reload the `ComboBoxModel` – MadProgrammer Mar 06 '13 at 10:35
  • This [Example](http://stackoverflow.com/questions/13699467/add-different-combobox-for-each-row-of-a-column-in-a-jtable/13703143#13703143) solves your problem. – Amarnath Mar 06 '13 at 19:00

1 Answers1

2

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;
    }
});
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138