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?
ImageIO.read
which will throw anIOException
when something goes wrong... – MadProgrammercardToDisplay
, but not adding to anything...this could be cause of your problem, but there is no context by which it would be possible to be sure. Consider providing a runnable example which demonstrates your problem. This will result in less confusion and better responses – MadProgrammercardToDisplay.setIcon(new ImageIcon(planechase.getFolderName() + "\\" + planechase.displayTopCard()));
... but as per my previous comment, there is no context to be sure that this is the correct thing to do in you case... – MadProgrammer