简体   繁体   中英

how is paint() running without being called in the main method?

This is a beginner question for java graphics using the awt package. I found this code on the web to draw some simple graphics.

import java.awt.*;
public class SimpleGraphics extends Canvas{

    /**
     * @param args
     */
    public static void main(String[] args) {
        SimpleGraphics c = new SimpleGraphics();
        c.setBackground(Color.white);
        c.setSize(250, 250);

        Frame f = new Frame();
        f.add(c); 
        f.setLayout(new FlowLayout()); 
        f.setSize(350,350);
        f.setVisible(true);
    }
    public void paint(Graphics g){
        g.setColor(Color.blue);
        g.drawLine(30, 30, 80, 80);
        g.drawRect(20, 150, 100, 100);
        g.fillRect(20, 150, 100, 100);
        g.fillOval(150, 20, 100, 100); 
    }
}

Nowhere in the main method is paint() being called on the canvas. But I ran the program and it works, so how is the paint() method being run?

The paint method is called by the Event Dispatch Thread (EDT) and is basically out of your control.

It works as follows: When you realize a user interface (call setVisible(true) in your case), Swing starts the EDT. This EDT thread then runs in the background and, whenever your component needs to be painted, it calls the paint method with an appropriate Graphics instance for you to use for painting.

So, when is a component "needed" to be repainted? -- For instance when

  • The window is resized
  • The component is made visible
  • When you call repaint
  • ...

Simply assume that it will be called, whenever it is necessary.

Actually you never invoke paint mathod yourself. It gets called automatically whenever the content pane of your frame needs to be repainted. It happens when your frame is rendered for the first time, resized, maximized (after being minimzed), etc.

If you are not aware of how AWT/Swing (render) painting API works then read this article - Painting in AWT and Swing .

The Paint Method Regardless of how a paint request is triggered, the AWT uses a "callback" mechanism for painting, and this mechanism is the same for both heavyweight and lightweight components. This means that a program should place the component's rendering code inside a particular overridden method, and the toolkit will invoke this method when it's time to paint. The method to be overridden is in java.awt.Component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM