简体   繁体   中英

JLabel Icon resisting change

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.

  • 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM