Search code examples
javaimageswingjpanelpaintcomponent

jPanel is not refreshing until I resize the app window


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.

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

I tried this and this but no change.

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

and in Window class/button method:

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

second attempt:

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

}

and Button:

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

Solution

  • 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();