Question

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?

Was it helpful?

Solution

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 methods 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 receives events and decide when to start the editing, 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 editing and get the value and use it to call the TableModel.setvalue... or cancel the editing.

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

OTHER TIPS

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

Try this: its working for me..click on the cell to see the combobox.

 private void comboloader() {
        try {
            TableColumn gradeColumn = jTable1.getColumnModel().getColumn(0);
            JComboBox comboBox = new JComboBox();

            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));
        } catch (Exception e) {
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top