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

前端 未结 3 667
余生分开走
余生分开走 2020-12-06 02:56

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 cla         


        
相关标签:
3条回答
  • 2020-12-06 03:25

    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.

    0 讨论(0)
  • 2020-12-06 03:33

    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.

    0 讨论(0)
  • 2020-12-06 03:36

    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.

    0 讨论(0)
提交回复
热议问题