rrazd
rrazd

Reputation: 1739

Why is paintComponent() run even though no one calls it?

I was wondering if someone could explain how/why paintComponent() is called right after all the statements in main() are run. The reason I am confused is that there is no explicit call to painComponent() but it is run regardless.

// JComponent is a base class for custom components 
public class SimpleDraw extends JPanel {
    public static void main(String[] args) {
        SimpleDraw canvas = new SimpleDraw();
        JFrame f = new JFrame("SimpleDraw"); // jframe is the app window
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(400, 400); // window size
        f.setContentPane(canvas); // add canvas to jframe
        f.setVisible(true); // show the window
    }
    // custom graphics drawing 
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g; // cast to get 2D drawing methods
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,  // antialiasing look nicer
                            RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setStroke(new BasicStroke(32)); // 32 pixel thick stroke
        g2.setColor(Color.BLUE); // make it blue
        g2.drawLine(0, 0, getWidth(), getHeight());  // draw line 
        g2.setColor(Color.RED);
        g2.drawLine(getWidth(), 0, 0, getHeight());  
    }
}

Upvotes: 1

Views: 284

Answers (1)

Paul Sasik
Paul Sasik

Reputation: 81459

Here is a decent little write-up on how paintComponent is handled.

Excerpt:

Who calls paintComponent

... This method is called because the user did something with the user interface that required redrawing, or your code has explicitly requested that it be redrawn. Called automatically when it becomes visible When a window becomes visible (uncovered or deminimized) or is resized, the "system" automatically calls the paintComponent() method for all areas of the screen that have to be redrawn. Called indirectly from a user-defined listener via repaint() ...

There's more in the write-up as well as some reference links, which, unfortunatelly, are all broken.

I also found this blog post which discusses painting/drawing in Java from a very basic point of view. Check out the first paragraph:

Why do we put all our graphical drawing code into a paintComponent() method? It seems odd, since it would seem we should be able to simply stick some simple graphics commands into our main() method in a Java application and just get the drawing done. Where does paintComponent come from? If we never call it in our code, how does it get executed?

In the Java docs you actually have to read up on paint to start getting an idea of what going on. The paintComponent documentation is not very helpful.

Upvotes: 4

Related Questions