user3758041
user3758041

Reputation: 179

How can I properly use my value as an argument to JComboBox.setModel()?

In the code below, I attempted to create a DefaultListModel object to use for my JComboBox.

Apparently, the setModel() method only accepts a object that is a ComboBoxModel. I attempted to convert it, and I got the exception, java.lang.ClassCastException.

I already searched up how to fix this specific problem, but I couldn't find anything helpful.

I then tried to create a ComboBoxModel object instead, yet I learned that this class is abstract. How can I bypass this problem, and get the valid argument for setModel()?

private void setComboBoxYears(int numberOfYears, JComboBox comboBox) {
        DefaultListModel<Integer> years = new DefaultListModel<>();
        for(int i = 1; i <= numberOfYears; i++)
            years.addElement(i);
        comboBox.setModel((ComboBoxModel) years);

Upvotes: 1

Views: 82

Answers (2)

Braj
Braj

Reputation: 46841

If you are looking for solution then try in this way:

final JComboBox<Integer> comboBox = new JComboBox<Integer>();
Integer[] years = new Integer[numberOfYears];
for (int i = 0; i < numberOfYears; i++)
    years[i] = i + 1;

comboBox.setModel(new DefaultComboBoxModel<Integer>(years));

Upvotes: 3

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

  1. Use a DefaultComboBoxModel instead.
  2. Please have a look at the API as all of this information can be gleaned from it by a simple glance.

Upvotes: 1

Related Questions