Java Swing Problem

2019-08-26 09:38发布

问题:

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:

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.



回答2:

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.