Reputation: 235
I have a JFrame
, and inside JFrame
is a JPanel
, and inside JPanel
are 12 JButton
s. I have set an ImageIcon
for each button.
Then, I need to give a JButton
a new ImageIcon
. I tried this:
buttons[0].setIcon(new ImageIcon("path/to/new/icon"));
But it didn't work. Also tried:
buttons[0].revalidate();
my_jpanel.revalidate();
So what am I forgetting about? Why it doesn't repaint?
Upvotes: 2
Views: 1124
Reputation: 32323
You should make sure you're loading the file you think you're loading. Try this:
ImageIcon icon = new ImageIcon("path/to/new/icon");
System.out.println(icon.getDescription());
This will be null
if the file is not loaded properly. If this is your problem, try using an absolute path (e.g. /home/waTEXmelon/program/blah.jpg
on Linux or C:\\Users\\waTEXmelon\\program\\blah.jpg
) on Windows.
If you are expecting the icon to be in your classpath, instead use:
new ImageIcon(getClass().getResource("/class/path/to/icon"));
You should also consider checking out ImageIO
to help prevent this problem in your future, it's more robust than the basic constructors.
If the above is not your problem, consider that Swing is not Thread Safe and you may be modifying the icon on a thread other than the Event Dispatch Thread. Try doing this:
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
buttons[0].setIcon(new ImageIcon("path/to/new/icon"));
}
}
If that still doesn't fix your problem, then the problem may be what @camrickr suggested, e.g. the JButton you're adding the icon to is not the one you think you're adding it to. To test this, both when you create the button, and when you update the icon, do a:
System.out.println(System.identityHashCode(button[0]));
If this doesn't match, then the buttons are not the same button.
Upvotes: 2