Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting JComboBox into JTable

I want to put individual JComboBoxes into each cells of a JTable. ie. The JComboBox content is not identical for each cell.

I basically would like to be able to just call the following code to add a row of JComboBox into the JTable. Anyone has any idea? Thanks

JComboBox cb1 = new JComboBox(...);
JComboBox cb2 = new JComboBox(...);
model.addRow(new Object[] {"Row name", cb1, cb2} );

JComboBox cb3 = new JComboBox(...);
JComboBox cb4 = new JComboBox(...);
model.addRow(new Object[] {"Row name 2", cb3, cb4} );

The closest example code I can find is as follows. But it is for where JComboBox content is identical for the individual column. Not the solution I need.

TableColumn col = table.getColumnModel().getColumn(vColIndex);
col.setCellEditor(new MyComboBoxEditor(values));

where

public class MyComboBoxEditor extends DefaultCellEditor {
    public MyComboBoxEditor(String[] items) {
        super(new JComboBox(items));
    }
}
like image 855
Dan Avatar asked Jan 19 '09 12:01

Dan


2 Answers

Extend JTable with this code:

@Override
public TableCellEditor getCellEditor(int row, int column) {
   Object value = super.getValueAt(row, column);
   if(value != null) {
      if(value instanceof JComboBox) {
           return new DefaultCellEditor((JComboBox)value);
      }
            return getDefaultEditor(value.getClass());
   }
   return super.getCellEditor(row, column);
}

This will create a unique JComboBox cell editor for each combo box you get the a value for.

like image 69
user74523 Avatar answered Oct 11 '22 14:10

user74523


I am sure this will solve your problem. Mention in which column you need to set the combo box in .getColumn(int column)

private void addComboToTable(JComboBox combo) {
    TableColumn gradeColumn = YourTable.getColumnModel().getColumn(0);
    JComboBox comboBox = combo;
    comboBox.removeAllItems();
    try {
        comboBox.addItem("Item 1");
        comboBox.addItem("Item 2");
        comboBox.addItem("Item 3");
    } catch (NullPointerException e) {
    } catch (Exception e) {
        e.printStackTrace();
    }
    gradeColumn.setCellEditor(new DefaultCellEditor(comboBox));
}
like image 23
Mujahid Avatar answered Oct 11 '22 13:10

Mujahid