1

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.

mechanicum
  • 699
  • 3
  • 14
  • 25

1 Answers1

4
  • 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);
  • use CardLayout with a few views, then any action is only to switch betweens cards

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

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • I was trying your suggestion, and I just noticed something awkward. The new images are there after all but right next to each other. It just added images side by side instead of replacing... – mechanicum Apr 03 '13 at 08:16
  • 1. then container.revalidate() and container.repaint() works in all cases, 2. final result depends od used LayoutManager for JPanel, 3. maybe use to JList, modify code example from JComboBoxand image renderer from Oracle tutorial – mKorbel Apr 03 '13 at 08:21
  • Yup, your answer showed the way. Apparently the panelPaintings added label components but never replaced them. **panelMain.remove(panelPainting);** was also unnecessary. Thank you. – mechanicum Apr 03 '13 at 08:38