guli Ver
guli Ver

Reputation: 1

Swing - Repainting of a Photo on JPanel

Hi guys, kindly ask you to help me .

Properly i need just to refresh JPanel with the different Photo gotten from files. 1st time during the adding of the JPanel with the photo on a frame - Photo is showed correctly ! everything is OK

but when i try to change the current Photo dynamically by another one and refresh the JPanel - i see the same (old) Photo. And does not matter the place where the following "refreshing" part of code is used:

picturePanel.repaint();

picturePanel.validate();

you can find below the code:

 // create the own JPanel
  public class ImagePanel extends JPanel {
      private Image image;
      public Image getImage() {
         return image;
      }
      public void setImage(Image image) {
         this.image = image;
      }
      @override
      public void paintComponent(Graphics g) {
         super.paintComponent(g);
         if (image != null) {
            g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
         } else
            System.out.println("The Picture is Missing!");
      }
   }

get the Photo from the file and add it to the own JPanel (ImagePanel)

public JPanel getTestPicture(String fromFile) {
      ImagePanel pp = new ImagePanel();
      pp.setLayout(new BorderLayout());
      try {
         pp.setImage(ImageIO.read(new File(fromFile)));
      } catch (IOException e) {
         e.printStackTrace();
      }
      return pp;
   }

and properly the main call of the JPanel:

picturePanel=getTestPicture("picture.jpg");
frame.add(picturePanel); //looks Correct - Photo is visible.

....

if we are trying to repaint the JPanel once more during the program old Photo stayed on the Panel. New photo is not painted.

picturePanel=getTestPicture("picture.jpg");
frame.add(picturePanel); //picture.jpg - it`s showed correctly!
picturePanel=getTestPicture("pic2.jpg");  
picturePanel.repaint(); 
picturePanel.validate();
//doesn`t work ! picture.jpg is on the JPanel still !

Please people help me with it ! i need to understand whats wrong in my code! please don`t propose to use JLabel or something similar.

THANK YOU IN ADVANCE !!!!!

Upvotes: 0

Views: 57

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347194

Don't add a new ImagePanel to the frame, update the existing one...

public class SomeOtherComponent extends JPanel {
    private ImagePanel imagePanel;
    //...
    public SomeOtherComponent() {
        //...
        imagePane = getTestPicture("picture.jpg");
        add(imagePane);
        //...
     }

When you need to change the image, simply use something like

imagePane.setImage(ImageIO.read(...));
imagePane.repaint();

Upvotes: 2

Related Questions