Hi,

In this code:

DrawPanel.java

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

public class DrawPanel extends JPanel
{
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

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

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


}

and this the application
DrawPaneTest.java

import javax.swing.JFrame;

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

        JFrame application = new JFrame();

        application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        application.add(panel);
        application.setSize(250,250);
        application.setVisible(true);
    }

}

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.

Recommended Answers

All 2 Replies

Member Avatar for harsh2327

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.