Wt Riker Wt Riker - 1 year ago 100
Java Question

Creating a DefauitComboBoxModel class

I need to create a bunch of JComboBoxes all alike. I am trying to use DefaultComboBoxModel to generate the model. However, I also need to create several different models based on the data to be included in the list. Therefore I created a class which I want to use to generate the model.

public class ModelComboBox<T> {

public ModelComboBox(ArrayList<String> list_) {
DefaultComboBoxModel<String> model=new DefaultComboBoxModel<String>();
for (String entry : list_) {

When I try to use the model I get a ModelComboBox.ModelComboBox cannot be resolved to a type error.

meatNames=new JComboBox<String>(new ModelComboBox.ModelComboBox<String>(meats));

Can someone help me with the syntax of telling it what the type is for ModelComboBox.ModelComboBox? I tried various placements of (DefaultComboBoxModel) in the argument but nothing I tried works. TIA.

Answer Source

There are many problems here.

First, ModelComboBox is a top-level class. The syntax for calling its constructor, as for any other top-level class, is new ModelComboBox<String>(), not new ModelComboBox.ModelComboBox<String>().

Second, this class is a generic class, but it doesn't use its generic type (T) anywhere. So it has absolutely no reason to be generic.

Third, its constructor creates a DefaultComboBoxModel, and assigns it to a local variable. When the constructor completes, the DefaultComboBoxModel thus goes out of scope, becomes eligible to GC, and is thus not usable anywhere.

Finally, you pass an instance of ModelComboBox to the constructor of JComboBox. But JComboBox expects an instance of ComboBoxModel, not an instance of ModelComboBox. So that can't compile.

You're completely overthinking this, IMO. All you need is some helper method allowing to take a List<String> and to create a DefaultComboBoxModel from that list:

public DefaultComboBoxModel<String> createComboBoxModel(List<String> list) {
    return new DefaultComboBoxModel<String>(new Vector<>(list));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download