Custom JPanel causing processing issues in second custom JPanel

Bit odd here. I have two classes extending from JPanel

, overriding paintComponent

in both. One implements Runnable

(for animation).

However, when used in conjunction with the Runnable

top on top, I get a wonderful "paint copy of everything the mouse points to" against the background of the instance Runnable

. See screenshots below:

using_a_jpanel

using a custom component

The only difference between them is what I use JPanel

in the former and a custom one JPanel

with a background image in the latter. The code for the second is JPanel

below:

package view.widgets;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class PaintedJPanel extends JPanel {

    private static final long serialVersionUID = 1L;
    private BufferedImage backgroundImage = null;

    public PaintedJPanel() {
        super();
    }

    public PaintedJPanel(File image) {
        super();
        try {
            backgroundImage = ImageIO.read(image);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        if(null != backgroundImage) {
            g2d.drawImage(backgroundImage, 0, 0, null);
        }
    }

    public BufferedImage getBackgroundImage() {
        return backgroundImage;
    }

    public void setBackgroundImage(BufferedImage backgroundImage) {
        this.backgroundImage = backgroundImage;
    }

}

      

EDIT : editing the details because the Enter key shouldn't send the question when I add tags.

COMPLETED EDIT @ 13: 38.

+3


source to share


1 answer


Ah, your paintComponent method there is no supercall. Change

@Override
protected void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    if(null != backgroundImage) {
        g2d.drawImage(backgroundImage, 0, 0, null);
    }
}

      

to



@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    if(null != backgroundImage) {
        g2d.drawImage(backgroundImage, 0, 0, null);
    }
}

      

As noted in my comments on your question (before looking at the code), without calling super, you break the drawing chain, which can lead to side effects with the rendering of child components.

+2


source







All Articles