views:

475

answers:

2

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");
+1  A: 

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.

oxbow_lakes
It starts with a slash if you want it absolute within the classpath and doesn't start with a slash if you want it relative to the class.
Joachim Sauer
I tried it, but I didn't work... I noticed it made it image move down a bit... but it didn't change it.
Then a common problem is that (if you're using an IDE) the png file isn't being copied into your output (or classes or bin) area. i.e. it's only in the source directory. That might be an IDE build setting - in IDEA it's under the "compiler" SETTINGS
oxbow_lakes
A: 

You can have a reference to the ImageIcon if you want to share it across buttons (instead of loading it everytime). To me your code should work. Maybe you can remove the current icon (using setIcon(null)) and then set it.

You don't need to remove the other icon first. Tony's PNG file is quite obviously not on his classpath
oxbow_lakes