Hello Java Developers,
I’ve never encountered this scenario so far. This scenario is:
(To make the scenario general for readers, lets have this illustration.)
We have this Box.png and Circle.png declared:
private final URL IMG1_DIRECTORY = Main.class.getResource("/res/Box.png");
private final URL IMG2_DIRECTORY = Main.class.getResource("/res/Circle.png");
Under our constructor:
try {
box = ImageIO.read(IMG1_DIRECTORY);
} catch (Exception e) {
// Our catchblock here
}
try {
circle= ImageIO.read(IMG2_DIRECTORY);
} catch (Exception e) {
// Our catchblock here
}
currentImg = box;
With the paint method, the box is drawn to our JPanel as shown in our Illustration 1.
@Override
public void paint(Graphics g) {
g.drawImage(currentImg, DEFAULT_LOCATION, DEFAULT_LOCATION, null);
}
Through a certain event, mousePressed in this example the Image will be changed.
@Override
public void mousePressed( MouseEvent e ) {
currentImg = circle;
repaint();
}
The desired output is shows in our Illustration 2. Unfortunately, the result happens to be the Illustration 3.
The question was:
– Why is the result happens to be both image overlaying each other?
– Another thing, if I have a code that will repaint the image to circle ( From Illustration 3 ) the box will just overlay the circle image.

super.paint, which, apart from a whole bunch of other important stuff, clears the graphics contextpaint, it’s normally preferred to use paintComponent, but make sure you callsuper.paintComponentThe graphic context is a shared resource and tends to be re-used between repaints, that means, because you didn’t clear the graphics context when you painted, you’ve got the previous “state”, which then paint over