简体   繁体   中英

Difference between paint() and repaint()

I am a novice Java programmer and I'm finding quite some difficulty in figuring out the actual difference between the functioning of the paint() and repaint() method.
Also in some of the programs that I studied I found paint() and repaint() interchangeable. Can someone please explain the difference? Thank you

Assuming that you are referring to the void paint(Graphics g) method that is declared in the Component class:

This paint method is called automatically, whenever it is necessary to paint (parts of) the component. For example, when the window was obstructed by another window and then becomes visible again: The window manager will determine this, and call paint on the top level component (eg a Frame) and this call will make its way down to the actual "bottom" components (eg a Button). The Graphics object that is passed to this method is provided by the Window manager, and corresponds to the area on the screen where the component should be painted. (And this Graphics object is only valid during the paint method).

In contrast to that, repaint() just triggers a new painting process. It is telling the system: "Please call paint on this component as soon as possible". You can call this method manually. And you can call it freuqently: The calls to repaint are coalesced . That means that when you issue many calls to repaint in a short period of time, then these calls may be summarized and may eventually only trigger one call to paint .

The paint method should not be called directly as the javadoc states:

Invoked by Swing to draw components. Applications should not invoke paint directly, but should instead use the repaint method to schedule the component for redrawing.

The repaint method should be used instead if you want the component to be repainted (redrawn). The javadoc also refers to the following documentation: Painting in AWT and Swing

paint() get called automatically at runtime. If you want to call paint() manually(again) then repaint() is used.

The paint() method contains instructions for painting the specific component.

The repaint() method, which can't be overridden, is more specific: it controls the update() to paint() process. You should call this method if you want a component to repaint itself or to change its look (but not the size).

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