I want to update an image in Java Swing and tried two different methods of rendering these images.
- Define a JLabel and set the icon of it
- Override the
paintComponent(Graphics g)
function in a custom JPanel and callg.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