Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is use of super.paint(g)?

Can someone explain me what is the use of super.paint(g) where, g is a Graphics variable in Applets or awt or swings or in Java.

I have done research and found that it is used to override but what is the use of this override?

I am a beginner. If possible can you explain the difference between paint(g) and super.paint(g) with a small example or please help me with this code?

/*
Let us consider this code 
This has only one paint declaration i.e; subclass's paint method declaration, no     declaration for superclass's paint function... when we explicitly call superclass's paint function 
what is the use of super.paint(g) and is it going to use superclass's paint declaration??
*/

import java.awt.*;
import java.applet.*;
/*
<applet code="superpaintDemo" height=768 width=1366>
</applet>
*/
class superpaintDemo extends Applet
{

    public void paint(Graphics g)
    {
        super.paint(g);
        g.drawString("This is Demo",200,200);
    }
}
like image 506
unknownerror Avatar asked May 02 '14 17:05

unknownerror


2 Answers

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.

Straight from the docs.

like image 149
Jeroen Vannevel Avatar answered Sep 24 '22 17:09

Jeroen Vannevel


  1. First, I add super.paint(g) in my own paint method.

When it repaints, things drawn before are cleared.

Sorry, I can't have the reputation to post more than 2 links.

  1. Then, I remove super.paint(g) in my own paint method.

    remove super.paint(g)

You can see things drawn on the Panel before are still there.

When you add super.paint(g), in your method it will call the method in the superclass of this subclass.My class RussiaPanel extends JPanel, and JPanel extends JComponent. It will invoke the "public void paint(Graphic g)" method in JComponet, and the things on the Panel will be cleared.For more details, you can refer to the API docs.

Hope to help you, and forgive my poor English.

like image 37
mztkenan Avatar answered Sep 24 '22 17:09

mztkenan