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
CodePudding user response:
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.
CodePudding user response:
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()
.