0

I want to update an image in Java Swing and tried two different methods of rendering these images.

  1. Define a JLabel and set the icon of it
  2. Override the paintComponent(Graphics g) function in a custom JPanel and call g.drawImage(img, 0, 0, null)

Rendering the first image works as expected in both ways, but if I'm trying to update the image, it doesn't replace but renders one layer above which is a problem, because the images I want to render are semi-transparent, so you can see the others through. I'm already using the repaint() method.

Method 1
public void setImage(Image img) {
    this.backgroundLabel.setIcon(new ImageIcon(img));
    this.repaint();
}
Method 2
public void setImage(Image img) {
    this.img = img;
    this.repaint();
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(img, 0, 0, null);
}

I'm thankful for any tips! <3

2 Answers2

1

The first thing line in paintComponent(Graphics g) should be

super.paintComponent(g);

This clears the panel, does any background painting if necessary, and any other support functions from the overridden paintComponent method. Otherwise, you will keep drawing images over the previous ones without first clearing them.

WJS
  • 36,363
  • 4
  • 24
  • 39
  • It is actually on top of the method. I only forgot to copy it as well. :) – DevOFVictory Apr 25 '22 at 19:17
  • 2
    Please provide a [mre] demonstrating the problem. Out of context snippets don't show the complete story. – WJS Apr 25 '22 at 20:21
  • 1
    For that MRE, either hot-link to images found in [this answer](https://stackoverflow.com/a/19209651/418556) or create them as the class is being constructed. Another tip: `g.drawImage(img, 0, 0, null);` should be `g.drawImage(img, 0, 0, this);` - ***every*** `JComponent` is an `ImageObserver`. – Andrew Thompson Apr 26 '22 at 02:28
1

For anyone in the future with the same problem, here is the answer I came up with. I didn't repainted the full frame, but only the JPanel. I had to add

frame.repaint();

in setImage().

  • Unfortunately, without the [mre] it doesn't really help much. Recommend you update your answer and use one of the images [Andrew Thompson](https://stackoverflow.com/users/418556/andrew-thompson) suggested. – WJS Apr 26 '22 at 15:35