Reputation: 709
I have an icon for a JLabel which I can see the change for only once. When blank, a new set image for the below code works as it should. But after that, the image is stuck. No new image can replace it. When I use repaint on panelPainting without revalidate(), I get no pictures at all. Thats also weird.
Here is the code, (panelMain houses panelPainting)
//get image from somewhere
JLabel imageLabel = new JLabel();
Icon imageIcon = new ImageIcon(image);
imageLabel.setIcon(imageIcon);
panelPainting.setAlignmentX(JLabel.CENTER);
panelPainting.add(imageLabel); // default center section
//my insanity starts here
panelPainting.revalidate();
panelMain.remove(panelPainting);
panelMain.revalidate();
EDIT: I double checked that the image does change every time.
Upvotes: 1
Views: 491
Reputation: 109823
use JLabel.setIcon()
as standard way, then there no reason to remove, modify and add a new JComponents
on runtime
in some cases there is issue with repainting Icon
in the JLabel
(from external sources, www sites, etc.), then you have to call,
myIcon.getImage().flush(); myLabel.setIcon(myIcon);
otherwise
have to call container.revalidate()
and container.repaint()
, as last code lines, one time, after all changes are done
for better help sooner post an SSCCE, short, runnable, compilable, just about JFrame with JLabel contains ImageIcon / Icon created on fly
Upvotes: 4