Andreas Fuglsang Andreas Fuglsang - 4 months ago 9
Java Question

Updating/recreating a JList

This is my first post here, and I am very green with Java. This is something I'm trying to make to improve my java knowledge.

I have a button, which when clicked produces a shuffled card deck as a Jlist.
When pressed again, I would very much like it to refresh the JList, or recreate it somehow. Instead, it simply
creates a new list, so I now have 2 JLists.

button1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{

cards.choseCards(); //Creates an ArrayList with the suffled cards
JList<String> displayList = new JList<>(cards.deck.toArray(new String[0]));
frame.add(displayList);
frame.pack();
cards.cleanUpDeck(); //Removes all the cards from the ArrayList
}
});

Answer

The key here is that Swing uses a model-view type of structure similar to model-view-controller (but with differences) where the model holds the data that the view (the component) displays.

What you are doing is creating an entirely new JList, but what you want to do is to update the model of the existing and displayed JList, either that or create a new model for this same existing JList. JLists use a ListModel for their mode, often implemented as a DefaultListModel object, and so you will want to update or replace this model such as by creating a new DefaultListModel object and then inserting it into the existing JList by calling its setModel(ListModel model) method.

For example your code could look something like this (made with lots of guesses since we don't know what your real code looks like):

button1.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // create new model for the JList
        DefaultListModel<String> listModel = new DefaultListModel<>();
        cards.choseCards(); //Creates an ArrayList with the suffled cards

        // add the cards to the model. I have no idea what your deck field looks like
        // so this is a wild guess.
        for (Card card : cards.deck) {
            listModel.addElement(card.toString());  // do you override toString() for Card? Hope so
        }

        // Guessing that your JList is in a field called displayList.
        displayList.setModel(listModel);  // pass the model in
        cards.cleanUpDeck(); //Removes all the cards from the ArrayList
    }
});
Comments