CNorlander CNorlander - 1 month ago 8
Java Question

Updating an Image as a background of a Jpanel Only works once?

I have the following code I found on this website. The code allows me to draw an image as the background of a JPanel. The issue I have is being able to update said image. The method I created is at the bottom and basically follows the code of the constructor but I cannot figure out why calling this code will not update my image after once use.

Basically using the setImg method only works the first time and thats it. If I call it again it does nothing.

Here is how I create the object

ImagePanel panel1 = new ImagePanel(new ImageIcon("src/title.png").getImage());


Here is how I am attempting to update it.

panel1.setImg(new ImageIcon("src/red.png").getImage());


Here is my object

import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image;

import javax.swing.ImageIcon; import javax.swing.JPanel;

class ImagePanel extends JPanel {

/** * */ private static final long serialVersionUID = 1L; private Image img;

public ImagePanel(String img) {
this(new ImageIcon(img).getImage()); }

public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null); }

public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null); }

public void setImg(Image img) {
this.img = img;
System.out.println("Img Set success");
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null); }
}

Answer

You need to call repaint() on the JPanel after changing its image so that it will draw the new image. Other problems:

  • Your paintComponent method needs to call the super.paintComponent(g) method on its first line in order to do "house-keeping" painting and to remove "dirty" pixels.
  • You're using null layouts -- shame on you.
  • Your indentation and code formatting is non-standard. This will make it hard for others (us) to understand your code and be able to help you. Learn and follow standard formatting rules.
  • If the JPanel is only going to show images and not hold components, then you're far better off using a JLabel and simply swapping ImageIcons.