Skip to content
Advertisement

Cannot display JComboBox in JTable with TableModel

Below code to display a JTable with 3 columns, which respectively contain a JComboBox, a String and a double, and which should display yellow. The problem is that I cannot get the JComboBox in the first column to display as … a combo box; instead I get a String saying “javax.swing.JComboBox...“. What am I doing wrong?

JavaScript

Advertisement

Answer

Never return a component in a TableModel. The whole point of having a separate model and view is that the model contains only data, not components. The model’s job is to provide data; the view’s job is to determine how to display that data.

Your TableModel’s getColumnClass method should look like this:

JavaScript

and your getValueAt method needs to return the actual data value at that row:

JavaScript

The cell renderer is part of the view, not the model, so it can make use of a JComboBox. Your render needs to use the value argument to modify your JComboBox:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement