开发者

Java Swing: repaint() vs invalidate [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Java Swing revalidate() vs repaint()

Hi all

I'm fighting with my program to make it refresh at the right time.

And not having a lot of success lol

I have 2 questions

Q1: which should I use when my interface has changed: repaint or invalidate?

Q2: when should they be called? I know it sounds stupid but I'm actually having problems because of SwingWorker and other t开发者_如何学JAVAhreaded operations.


Q1: which should I use when my interface has changed: repaint or invalidate?

If the layout is not up to date because of resizing , font change etc then you should call invalidate. Invalidating a component, invalidates the component and all parents above it are marked as needing to be laid out. Prior to painting, in the validation step if no change is found then the paint step is left out.

If there is some part of component which is being updated (defined by the graphic's clip rectangle, called "damaged" region) then you should consider calling repaint. One of the reason a damaged regions may occur is from the overlapping of a part of your component because of some other component or application. As per my experience the repaint() is more effective if you call it on the innermost enclosing component (i.e. using public void repaint(int x, int y, int width, int height) rather than using public void repaint()).

Q2: when should they be called?

Invalidate(): marks a component as not valid -- that means, it's layout is or may not be "up to date" anymore: i.e. the component is resized, a border is added, it's font changes, etc. you should never need to call invalidate() by hand, as swing does that for you on pretty much for every property change.

When more than one region within the control needs repainting, Invalidate will cause the entire window to be repainted in a single pass, avoiding flicker caused by redundant repaints. There is no performance penalty for calling Invalidate multiple times before the control is actually repainted.

Repaint() : If the component is a lightweight component, this method causes a call to this component's paint method as soon as possible. Otherwise, this method causes a call to this component's update method as soon as possible.

Also have look at Update method.

NOTE: Swing processes "repaint" requests in a slightly different way from the AWT, although the final result for the application programmer is essentially the same -- paint() is invoked.

Refer to the link below for an excellent link on how painting is done in AWT and Swing:

http://www.oracle.com/technetwork/java/painting-140037.html

Hope this will help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜