Search code examples
javaswinglabeljpanelremoveall

JPanel.removeAll() not functioning properly


So I'm currently teaching myself to use GUI, and I decided to go back to the code for a game of Go Fish that I created and add in a GUI to it. For the panel that holds the CPU Player's cards, it displays the back of some playing cards to indicate the size of the CPU's hand.

Whenever a change occurs in the CPU's hand size, my method updateComputerCards gets called to adjust the amount of cards appearing on the screen. It does this by calling the removeAll() method for my panel, and then proceeds to re-add the proper amount of card images.

My issue though, is that when the game first begins, and matches are found within the CPU's hand, the method works as intended, and the amount of cards appearing shrinks. However, every subsequent time that the method is called, nothing changes in the GUI despite the CPU having a hand of cards of a different size.

Through the debugger I can see that the removeAll() method is not removing all the components on the panel for some reason, even though it succeeds in doing so without issue the first time it is called. Can anyone help me out here?

    public void updateComputerCards(ArrayList<Integer> hand) {
        labelPanel.removeAll();
        for (int i = 0; i < hand.size(); i++) {
            labelPanel.add(computerCardLabels.get(i));
            labelPanel.add(b.createHorizontalStrut(10));
        }

    }

Solution

  • You need to call the repaint() method after making the changes. See Painting in AWT and Swing.