Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...