Java Swing Problem

痞子三分冷 提交于 2019-12-24 20:12:48

问题


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.



来源:https://stackoverflow.com/questions/628290/java-swing-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!