views:

350

answers:

2

I want to add combobox into a cell of JTable.

   model=new DefaultTableModel(data,col);
   JTableHeader head=new JTableHeader();
   head.setBackground(Color.BLUE);
   table=new JTable(model);
   table.add(head);
    JComboBox combo = new JComboBox();
    combo.addItem("Names");
    combo.addItem("Antony");
    combo.addItem("Victor");
    combo.addItem("Ramkumar");
    table.add(combo);

But i cant get the combobox in the cell. Is it possible to set combo box?

+2  A: 

Take alook at this Java tutorial and search in this page for "Using a Combo Box as an Editor"

Argiropoulos Stavros
A: 

You need to set the TableCellEditor of the JTable. It's better to search the java Tutorials, but here is a short explain.

JTable uses three main classes to work:

1) TableModel: it's function is to say how many rows and columns the table has and to serve the data of the Table, it's main mehtods are getValue(row,col) and setValue(value, row,col). And fire events to notify the JTable repaints.

2) TableCellRenderer: it's main purpose it's to draw components in the JTable's cells. This components are only painted: NOT WORK! if you draw a JComboBox it won't desplegate if you click on it or if you draw a JCheckbox it wont't select/unselect.

3) TableCellEditor: it's main purpose it's to draw a component within a JTableCell to edit the value of the cell. It recives events and decide when to start the editting, then it's getTableCellEditorComponent method is called to return the editor component. The component returned has to launch events so that the TableCellEditor knows when to stop the editting and get the value and use it to call the TableModel.setvalue... or cancel the editting.

So that to show JComboBox in a JTable you must create your own TableCellEditor, not an easy task if you havent done it before.

Telcontar