Reputation: 43
I'm writing an application that creates a deck of cards in a random order and when a button is pressed moves the top card to the bottom and shows the new top card. (It's to simulate a Planechase deck to those familiar with Magic: the Gathering.) When the button is pressed it is properly cycling through the image files, but when I assign an image to a JLabel with an ImageIcon I can't get the JLabel to refresh with the new image. Here's the code I'm using to refresh
nextCardButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
planechase.topCardIncrement();
createCardToDisplay();
}
});
planechase is an instance of a class CardDeck which stores the randomized deck and has several methods to shuffle, change cards, etc. topCardIncrement() changes the top card to the next in the list.
private void createCardToDisplay()
{
cardToDisplay = new JLabel(new ImageIcon(planechase.getFolderName() + "\\" + planechase.displayTopCard()));
}
createCardToDisplay assigns cardToDisplay to an image derived from the folder name of the images and the current file. cardToDisplay is placed within JPanel contentPanel which is placed within JFrame frame. I can't figure out the proper way to repaint/revalidate (I'm not quite clear on what the difference is) my GUI to reflect the updated image. I've confirmed via System.out.println calls that
planechase.getFolderName() + "\\" + planechase.displayTopCard()
is updating as it should, so I assume that the JLabel is being reassigned properly. What is the proper way to redraw this so that it reflects the new ImageIcon?
Upvotes: 0
Views: 692
Reputation: 347334
The code is ambiguous...
The first thing that jumps out at me is...
private void createCardToDisplay()
{
cardToDisplay = new JLabel(new ImageIcon(planechase.getFolderName() + "\\" + planechase.displayTopCard()));
}
This is creating a new instance of cardToDisplay
, but is it been added anywhere? Is the previous instance been removed? There's no context to be certain.
Normally, when you want to change the icon of a JLabel
, you would simply call setIcon
on the instance of the JLabel
...
cardToDisplay.setIcon(new ImageIcon(planechase.getFolderName() + "\\" + planechase.displayTopCard()));
Because this is a bound field, it will trigger a repaint request automatically.
Upvotes: 1