问题
Can anyone tell me exactly how does the paint() method in java applet work, in simple words? Like, when it will be called , how it will be called? Because sometimes it gets called multiple times and I do not know how that happens.
回答1:
To understand this you need to know Applet Lifecycle..
Life Cycle of an Applet:
Four methods in the Applet class give you the framework on which you build any serious applet:
1) init: This method is intended for whatever initialization is needed for your applet. It is called after the param tags inside the applet tag have been processed.
2) start: This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other pages.
3) stop: This method is automatically called when the user moves off the page on which the applet sits. It can, therefore, be called repeatedly in the same applet.
4) destroy: This method is only called when the browser shuts down normally. Because applets are meant to live on an HTML page, you should not normally leave resources behind after a user leaves the page that contains the applet.
5) paint: Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser. The paint() method is actually inherited from the java.awt.
The second case, when paint() calls are genereted is when the program calls repaint() or update(). The repaint() method is the one invoked by a program to do drawing. Their are 4 versions of this method but the one with no arguments is usually used. Drawing via repaint() most often takes place in response to user input.
repaint() ==> update() ==(usually calls)==> paint()
repaint() does not invoke paint() directly. It schedules a call to an intermediate method, update(). Finally, update() calls paint() (unless you override update).
来源:https://stackoverflow.com/questions/15977233/how-does-paint-work