Question

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);
    }
}
Était-ce utile?

La solution 2

  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.

Autres conseils

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.

I guess its usage is like some other methods that you use super.method(). This is used to invoke the method in the super class. Basically it depends on your purpose and you decide how to use use it. In most case, we override the paint(Graphics g) in our subclass of the Component to fulfill our intention. If you call super.paint(g), it might call the method in the super class of this subclass.

You should call super.paintComponent(g) if you want the super class to paint first (or last);

calling super.paint(g) would cause nasty recursion in Swing.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top