摇摆 - 在 JPanel 上重新绘制照片



大家好,请你们帮助我。

正确地,我只需要使用从文件中获取的不同照片刷新JPanel。第一次在添加带有相框照片的JPanel期间 - 照片显示正确!一切都很好

但是当我尝试用另一张照片动态更改当前照片并刷新JPanel时 - 我看到相同的(旧)照片。并且使用以下代码的"刷新"部分的位置无关紧要:

picturePanel.repaint();

picturePanel.validate();

您可以在下面找到代码:

 // 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!");
      }
   }

从文件中获取照片并将其添加到自己的 JPanel (图像面板

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;
   }

以及 JPanel 的主要调用:

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

....

如果我们试图在程序期间再次重新粉刷 JPanel 旧照片留在面板上。新照片未绘制。

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 !

请人们帮助我! 我需要了解我的代码中出了什么问题! 请不要建议使用 JLabel 或类似的东西。

提前谢谢你

!!!!

不要向框架添加新的ImagePanel,更新现有的

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

当您需要更改图像时,只需使用类似

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

最新更新