Home > OS >  Updating an image in Java Swing shows strange behaviour
Updating an image in Java Swing shows strange behaviour

Time:04-27

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

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().

  • Related