在调整应用程序窗口大小之前,jPanel不会刷新 [英] jPanel is not refreshing until I resize the app window

查看:221
本文介绍了在调整应用程序窗口大小之前,jPanel不会刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的jPanel有一个问题。
我有一个按钮,其中PNG图像来自String输入(数学公式),然后它将重新绘制jPanel中的旧图像。这就是问题所在。图像已更改,但jPanel不会重新绘制,直到我手动调整应用程序窗口大小。

I have one problem with my jPanel. I have a button which PNG image from String input (math formula) and then it will repaint the old image in jPanel. And there goes the problem. The image got changed, but the jPanel wont repaint until I manually resize the app window.

看起来Panel不会重新绘制,直到调整大小。但我不知道如何在该按钮中执行此操作。

Looks like the Panel wont repaint until that resizing. But I have no idea how to do it in that button.

我试过这个但没有变化。

btw。我在netbeans中使用GUI Builder。

btw. I am using GUI Builder in netbeans.

我的代码......第一次尝试:

My code... first attempt:

public class ImagePanel extends JPanel {

   private String path;
   Image img;
   public ImagePanel() {
        try {
            //save path
            path = "Example5.png";
            //load image
            img = ImageIO.read(new File(path));
        } catch (IOException ex) {
        }
    }
   @Override
   public void paint(Graphics g) {
      //draw the image
      if (show) {
        try {
            if (img != null) {
                img = ImageIO.read(new File(path));
                g.drawImage(img, 0, 0, this);
            }
        } catch (IOException ex) {
        }
     } else {
        show = true;
     }
   }
}

和窗口类/按钮方法:

   imagePanel = new ImagePanel();
   imagePanel.repaint();
   imagePanel.updateUI();

第二次尝试:

public class ImagePanel extends JPanel {

   private String path;
   Image img;
   ImagePanel(Image img) {
        this.img = img;
   }

   public void setImg(Image img) {
       this.img = img;
   }

   @Override
   public void paintComponent(Graphics g) {
       super.paintComponent(g);

       // Draw image centered in the middle of the panel
       g.drawImage(img, 0, 0, this);
   }

}

和按钮:

imagePanel.setImg(new ImageIcon("2.png").getImage());
imagePanel.repaint();


推荐答案

你可以用一个背景重绘线程来处理这个问题。您可以将它放在JPanel子类的构造函数中。

You can take care of this with a backround repaint thread. You can place this in the constructor of your JPanel subclass.

Thread repainter = new Thread(new Runnable() {
    @Override
    public void run() {
        while (true) { // I recommend setting a condition for your panel being open/visible
            repaint();
            try {
                Thread.sleep(30);
            } catch (InterruptedException ignored) {
            }
        }
    }
});
repainter.setName("Panel repaint");
repainter.setPriority(Thread.MIN_PRIORITY);
repainter.start();

这篇关于在调整应用程序窗口大小之前,jPanel不会刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆