Java Swing Problem

classloaderjavaresourcesswing

I have a board with cards in which I have to find matches. I have two variables buttonA and buttonB to keep track of the squares clicked.

When they are equal I can remove them from the board by simply adding this code:

cards[buttonA].setVisible(false);
cards[buttonB].setVisible(false);

How can I place the same image on all the buttons after finding matches?
I tried the following but it instead of changing the image simply leaves the same image on the buttons

cards[buttonA].setIcon(new ImageIcon("myPic.png");

Best Solution

You probably need to use:

new ImageIcon(getClass().getResource("/path/to/myPic.png"));

Where this resource is on the classpath. (Remember if using an IDE you need to make sure that your PNG resources get copied over to the output directory. In IDEA for example, this is achieved in the compiler settings menu)

edit: I can never remember whether the path starts with a / or not.