Search code examples
javaswingarraylistjlistdefaultlistmodel

Why is my DefaultListModel not showing up on my JList?


I have the following method.

           DefaultListModel getModelForCabin(Cabin cabin) {

 List<Camper> listAdded= new ArrayList<Camper>(getOrCreateGroup(cabin));

 DefaultListModel<Camper> dfm= new DefaultListModel<Camper>();
    for(Camper c: listAdded){
        if(!dfm.contains(c)){
            dfm.addElement(c);
        }

    }
    //System.out.println(listAdded);
    //System.out.println(dfm);

    return dfm;
}

Then, I set this method inside the JList like this...

 JList list = new JList(getModelForCabin((Cabin)comboBox.getSelectedItem()));
scrollPane_1.setViewportView(list);

In the method, if I print the dfm and listAdded as shown in the system print line, it shows the both.

If I type this...

System.out.println(getModelForCabin((Cabin)comboBox.getSelectedItem());   

It prints out the model as well.

What it will not do though, is add the model to the JList. I've tried changing around the code, deleting the JList and making a new one, and rearranging the code.

No matter what I do, it will not work.

So my list prints fine, my DefaultListModel prints fine, my HashMap that prints the Cabin and Campers works fine, but the JList will not print the model.

Added:

     JScrollPane scrollPane_1 = new JScrollPane();
    scrollPane_1.setBounds(361, 205, 296, 339);
    getContentPane().add(scrollPane_1);

     list = new JList(getModelForCabin((Cabin)comboBox.getSelectedItem()));
    scrollPane_1.setViewportView(list);

Solution

  • I figured out the problem was because I wasn't setting the model. If the model is a local DefaultListModel, it has to be set in the main class using the setModel method.

    I needed to reference the JList, then do the setModel like this....

                list.setModel(getModelForCabin((Cabin)comboBox.getSelectedItem()));
    

    Where list is the variable of the JList, and getModelForCabin(Cabin cabin) is the method which returns the DefaultListModel.

    It was added to both the action listener for the add button, as well as a refresh button that was created when opening the class.