开发者

Java: Using multiple Threads to paint simultaniously on a JPanel

I have a JPanel on which I wish to have several threads painting "animations" on. An "animation" consists of a JLabe开发者_StackOverflow中文版l with an ImageIcon on it, which is being moved from one area of the screen to another area.

Now, problem is - I want several such animations to be portrayed on screen by those threads mentioned. Problem is - the JPanel's "paint()" method can only be trigged by one thread at a time - causing the animations to execute serially, instead of in a parallel way.

Any idea how to have several such animations on screen at the same time?


It is impossible to use multiple threads to do what you want. Swing Toolkit is single threaded . The correct way to do it is to use one of the animation frameworks available:

  • Trident animation framework
  • TimingFramework


Swing is not thread-safe, thus it's simply not a supported use-case to do UI-related stuff from several threads simultaneously.

Go for the model-view-controller (MVC) pattern:

  • Let all threads update a (thread safe) model.
  • Whenever there is an update of the model, invoke repaint.
  • repaint() will schedule the UI-thread to call the proper paint-methods.
  • The paint-method should then simply read the state of the model, and draw the component accordingly.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜