4

I've a JComboBox in 3rd and 4th column of a JTable but I don't know how to get its items...the problem isn't the method to get items but the cast

JComboBox combo=(JComboBox) jTable1.getColumnModel().getColumn(3).getCellEditor();

Can you help me please?

mKorbel
  • 109,525
  • 20
  • 134
  • 319

3 Answers3

5

The JComboBox is wrapped in a CellEditor. You must retrieve the wrapped component, for example when using DefaultCellEditor:

DefaultCellEditor editor = (DefaultCellEditor)table.getColumnModel().getColumn(3).getCellEditor();
JComboBox combo = (JComboBox)editor.getComponent();
Sébastien Le Callonnec
  • 26,254
  • 8
  • 67
  • 80
  • it works but it deletes items of all combobox of all rows...i've tried with : DefaultCellEditor editor (DefaultCellEditor)jTable1.getCellEditor(0, 3); JComboBox combo = (JComboBox)editor.getComponent(); combo.removeItemAt(combo.getSelectedIndex()); – Francesco Stranieri Mar 30 '13 at 12:05
  • Not sure I understand: are you trying to delete items of a combo box in a given row? – Sébastien Le Callonnec Mar 30 '13 at 14:14
  • yes, i want to delete a specific item of the combobox in a specific row (i do it with double click of mouse so i want to delete the selected element) – Francesco Stranieri Mar 30 '13 at 18:02
0

Read this tutorial on how to use JCombobox as editor in JTable.
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#combobox

prasanth
  • 3,502
  • 4
  • 28
  • 42
0

Try something like this:

 public void example(){  

      TableColumn tmpColum =table.getColumnModel().getColumn(1);
      String[] DATA = { "Data 1", "Data 2", "Data 3", "Data 4" };
      JComboBox comboBox = new JComboBox(DATA);

      DefaultCellEditor defaultCellEditor=new DefaultCellEditor(comboBox);
      tmpColum.setCellEditor(defaultCellEditor);
      tmpColum.setCellRenderer(new CheckBoxCellRenderer(comboBox));
      table.repaint();
   }


/**
   Custom class for adding elements in the JComboBox.
*/
class CheckBoxCellRenderer implements TableCellRenderer {
        JComboBox combo;
        public CheckBoxCellRenderer(JComboBox comboBox) {
            this.combo = new JComboBox();
            for (int i=0; i<comboBox.getItemCount(); i++){
                combo.addItem(comboBox.getItemAt(i));
            }
        }
        public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            combo.setSelectedItem(value);
            return combo;
        }
    }
Adrian
  • 655
  • 6
  • 10