Reputation: 179
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
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
Reputation: 285403
Upvotes: 1