Tushar Sharma
Tushar Sharma

Reputation: 302

Which statement clears the previous Graphics and draw a new One in Java?

This is The Code :

public void paint(Graphics g) {
    g.fillOval(x, y, 25, 25);

    repaint();

}

This will create an output like This where if i move the pointer it doesn't clear the previous Graphics and creates a Path .

Output of Above Code

And by adding the super statement like this it Doesn't show the Path but only the Current location of the Oval Graphic.

public void paint(Graphics g) {
    super.paint(g);
    g.fillOval(x, y, 25, 25);

    repaint();

}

The output is This

I just want to the Mechanism and The Reason Behind This.

Upvotes: 1

Views: 110

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Sorry, but there is so much wrong with your code, that we have to fix it:

  • First off, don't override a JComponent's (or JFrame's) paint method but rather override the JComponent's or JPanel's paintComponent. This way you avoid mistakingly messing up painting of borders or child components, both of which paint is responsible for. Also since paintComponent has automatic double buffering, your animation will be much smoother.
  • Next, you almost always do want to call the super's painting method, which for paintComponent is super.paintComponent(g) as this will continue to propagate the painting chain, whereas by not calling this you break this chain. Calling the super's method will call the component's housekeeping painting including the overpainting of "dirty" pixels which is why the trails are removed. This is likely the answer that you're looking for.
  • Most important never call repaint() from within any painting method. Doing this results in a poor-man's animation that is completely uncontrollable, and puts too much responsibility on the painting method which should focus on its sole job -- to paint the component. Use a game loop such as a Swing Timer instead.

Most important -- read the tutorials as most of this is already explained there:

Upvotes: 3

FallAndLearn
FallAndLearn

Reputation: 4135

Straight from the docs

public void paint(Graphics g)

Paints the container. This forwards the paint to any lightweight components that are children of this container. If this method is reimplemented, super.paint(g) should be called so that lightweight components are properly rendered. If a child component is entirely clipped by the current clipping setting in g, paint() will not be forwarded to that child.

As he said that super.paint() cleans the dirty pixels. This says it all .!! :)

Upvotes: 2

Related Questions