It took me very little effort to put a JComboBox in a JTable so that when the cells in a certain column are clicked, it lets the user choose from a drop down list of items. However, my program requires that the underlying combo box can change, since the list that the combo box relies on can change. How can I make this happen? I tried some various things, such as the following, but with no luck. Didn't really expect it to work anyway, considering the return type of getCellEditor. .

javax.swing.table.TableColumn doctorColumn = jTable1.getColumnModel().getColumn(1);
        javax.swing.JComboBox box = (javax.swing.JComboBox)doctorColumn.getCellEditor();
        box.removeAllItems();
        java.util.Vector<Doctor> docs = Application.readDoctors();
        for (Doctor d: docs){
            box.addItem(d.readName().toString());
        }

Well, I decided to take the easy way out and just re-set the editor using the same code that I originally used to do it. But it would be nice to have a listener that just updates the editor whenever it changes instead.

What is drives the change in the combo box entries? You can change the values in the combo box model pretty easily as needed. Here is an example that updates the values in the combo based upon the value in another table column (the "Vegetarian" column in this case). The bulk of the code is Sun's TableRenderDemo code (hence the big copyright notice, sorry, I just wanted a chunk of table model code I could edit real quick for an example). I added the "ComboEditor" class and used that in place of the DefaultCellEditor. Relevant changes in bold:

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


/*
 * TableRenderDemo.java requires no other files.
 */

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.DefaultComboBoxModel;

/**
 * TableRenderDemo is just like TableDemo, except that it
 * explicitly initializes column sizes and it uses a combo box
 * as an editor for the Sport column.
 */
public class TableRenderDemo extends JPanel {
    private boolean DEBUG = false;

    public TableRenderDemo() {
        super(new GridLayout(1,0));

        JTable table = new JTable(new MyTableModel());
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Set up column sizes.
        initColumnSizes(table);

        //Fiddle with the Sport column's cell editors/renderers.
        setUpSportColumn(table, table.getColumnModel().getColumn(2));

        //Add the scroll pane to this panel.
        add(scrollPane);
    }

    /*
     * This method picks good column sizes.
     * If all column heads are wider than the column's cells'
     * contents, then you can just use column.sizeWidthToFit().
     */
    private void initColumnSizes(JTable table) {
        MyTableModel model = (MyTableModel)table.getModel();
        TableColumn column = null;
        Component comp = null;
        int headerWidth = 0;
        int cellWidth = 0;
        Object[] longValues = model.longValues;
        TableCellRenderer headerRenderer =
            table.getTableHeader().getDefaultRenderer();

        for (int i = 0; i < 5; i++) {
            column = table.getColumnModel().getColumn(i);

            comp = headerRenderer.getTableCellRendererComponent(
                                 null, column.getHeaderValue(),
                                 false, false, 0, 0);
            headerWidth = comp.getPreferredSize().width;

            comp = table.getDefaultRenderer(model.getColumnClass(i)).
                             getTableCellRendererComponent(
                                 table, longValues[i],
                                 false, false, 0, i);
            cellWidth = comp.getPreferredSize().width;

            if (DEBUG) {
                System.out.println("Initializing width of column "
                                   + i + ". "
                                   + "headerWidth = " + headerWidth
                                   + "; cellWidth = " + cellWidth);
            }

            column.setPreferredWidth(Math.max(headerWidth, cellWidth));
        }
    }

    public void setUpSportColumn(JTable table,
                                 TableColumn sportColumn) {
        //Set up the editor for the sport cells.
        sportColumn.setCellEditor([B]new ComboEditor()[/B]);

        //Set up tool tips for the sport cells.
        DefaultTableCellRenderer renderer =
                new DefaultTableCellRenderer();
        renderer.setToolTipText("Click for combo box");
        sportColumn.setCellRenderer(renderer);
    }

    [B]/** Custom editor that changes the combo choices based 
     * on the "Vegetarian" column value 
     */
    class ComboEditor extends DefaultCellEditor{
        DefaultComboBoxModel model;
        Map<String,List<String>> choicesMap;

        public ComboEditor(){
            super(new JComboBox());
            model = (DefaultComboBoxModel)((JComboBox)getComponent()).getModel();
            buildComboMap();
        }

        private void buildComboMap(){
            choicesMap = new HashMap<String,List<String>>();
            // for "true"
            List<String> choices = new ArrayList<String>();
            choices.add("Knitting");
            choices.add("Interior Decoration");
            choicesMap.put("true", choices);
            // for "false"
            choices = new ArrayList<String>();
            choices.add("Football");
            choices.add("Hockey");
            choices.add("Kickboxing");
            choicesMap.put("false", choices);
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            model.removeAllElements();
            String keyColumnValue = table.getValueAt(row, table.getColumnModel().getColumnIndex("Vegetarian")).toString();
            for (String item : choicesMap.get(keyColumnValue)){
                model.addElement(item);
            }
            return super.getTableCellEditorComponent(table, value, isSelected, row, column);
        }
    }[/B]

    class MyTableModel extends AbstractTableModel {
        private String[] columnNames = {"First Name",
                                        "Last Name",
                                        "Sport",
                                        "# of Years",
                                        "Vegetarian"};
        private Object[][] data = {
            {"Mary", "Campione",
             "Football", new Integer(5), new Boolean(false)},
            {"Alison", "Huml",
             "Interior Decoration", new Integer(3), new Boolean(true)},
            {"Kathy", "Walrath",
             "Hockey", new Integer(2), new Boolean(false)},
            {"Sharon", "Zakhour",
             "Knitting", new Integer(20), new Boolean(true)},
            {"Philip", "Milne",
             "Kickboxing", new Integer(10), new Boolean(false)}
        };

        public final Object[] longValues = {"Sharon", "Campione",
                                            "None of the above",
                                            new Integer(20), Boolean.TRUE};

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }

        /*
         * JTable uses this method to determine the default renderer/
         * editor for each cell.  If we didn't implement this method,
         * then the last column would contain text ("true"/"false"),
         * rather than a check box.
         */
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        /*
         * Don't need to implement this method unless your table's
         * editable.
         */
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            if (col < 2) {
                return false;
            } else {
                return true;
            }
        }

        /*
         * Don't need to implement this method unless your table's
         * data can change.
         */
        public void setValueAt(Object value, int row, int col) {
            if (DEBUG) {
                System.out.println("Setting value at " + row + "," + col
                                   + " to " + value
                                   + " (an instance of "
                                   + value.getClass() + ")");
            }

            data[row][col] = value;
            fireTableCellUpdated(row, col);

            if (DEBUG) {
                System.out.println("New value of data:");
                printDebugData();
            }
        }

        private void printDebugData() {
            int numRows = getRowCount();
            int numCols = getColumnCount();

            for (int i=0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j=0; j < numCols; j++) {
                    System.out.print("  " + data[i][j]);
                }
                System.out.println();
            }
            System.out.println("--------------------------");
        }
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("TableRenderDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        TableRenderDemo newContentPane = new TableRenderDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Thanks for the response. I'm a bit late replying, appreciate if you'd check this logic. (And yes, what I was trying to do is what you said: change the combo box entries based on what's in some list - so when the list changes, so do the combo box entries).

So from my understanding, the getTableCellEditorComponent method is what gets called when the user clicks on a cell of the JTable, and inside that method, you are updating the JComboBox by removing everything from it and then adding all the elements from the Vegetarian column to it?

So from my understanding, the getTableCellEditorComponent method is what gets called when the user clicks on a cell of the JTable, and inside that method, you are updating the JComboBox by removing everything from it and then adding all the elements from the Vegetarian column to it?

Mostly correct, yes. I'm removing the elements from the ComboBoxModel and adding the contents of a List of entries that is mapped to the value of the Vegetarian column. So the Map contains one List for the value "true" and another for the value "false".

You could just as easily store two(or more) separate models in the map and not even bother with the clear/add part - just pull the model from the map and use setModel() to swap it directly.

Mostly correct, yes. I'm removing the elements from the ComboBoxModel and adding the contents of a List of entries that is mapped to the value of the Vegetarian column. So the Map contains one List for the value "true" and another for the value "false".

You could just as easily store two(or more) separate models in the map and not even bother with the clear/add part - just pull the model from the map and use setModel() to swap it directly.

So how would you work this if each row will contain need to have different values (pulled from a database)? In my head I keep thinking that I could just do some sort of comboBox.add("value1") (and repeat/change for each row) type of thing, but I'm an ASP guy and this Java is kicking my butt.

Oops, just realized that I never marked this as solved. I'll do that now. Paul - you should start a new thread and describe exactly what you're trying to do and what problem you're facing. You can continue in here if you want, but it will be much harder to get replies.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.