Search code examples
javaswingexceptioncomboboxdefaultlistmodel

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);

Solution

    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.