In this code:


import java.awt.Graphics;
import javax.swing.JPanel;

public class DrawPanel extends JPanel
    public void paintComponent(Graphics g)

        int width = getWidth();
        int height = getHeight();

        g.drawLine(0, 0, width, height);
        g.drawLine(0, height, width, 0);


and this the application

import javax.swing.JFrame;

public class DrawPaneTest {
    public static void main(String args[])
        DrawPanel panel = new DrawPanel();

        JFrame application = new JFrame();




1- Who calls the method paintComponent() ?
2- What the purpose of super.paintComponent(g) and why there is no difference between keeping it or removing it from the source?

Any help is appreciated.

Answer to Q2>

Method paintComponent(Graphics g) is already defined in JPanel class. What you are doing is OVERRIDING paintComponent() of JPanel. So, when paintComponent() is called, your overridden method(that is defined by you) is called and not that under JPanel class.

When you specify the keyword "super(g)", the paintComponent() in JPanel class is called and the original paintComponent() method is also executed.

This is very useful because you don't have to re-write the entire code which is already written in paintComponent() of JPanel class.

Hope you got it now.

This article has been dead for over six months. Start a new discussion instead.