简体   繁体   English

Java:使用多个线程在JPanel上同时绘制

[英]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. 我有一个JPanel,我希望有几个线程绘制“动画”。 An "animation" consists of a JLabel with an ImageIcon on it, which is being moved from one area of the screen to another area. “动画”由一个带有ImageIcon的JLabel组成,它正从屏幕的一个区域移动到另一个区域。

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. 问题是 - JPanel的“paint()”方法一次只能由一个线程触发 - 导致动画以串行方式执行,而不是以并行方式执行。

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 . Swing Toolkit是单线程的。 The correct way to do it is to use one of the animation frameworks available: 正确的方法是使用其中一个可用的动画框架:

Swing is not thread-safe, thus it's simply not a supported use-case to do UI-related stuff from several threads simultaneously. Swing不是线程安全的,因此它不是一个支持的用例来同时从几个线程做与UI相关的东西。

Go for the model-view-controller (MVC) pattern: 转到模型 - 视图 - 控制器(MVC)模式:

  • 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. repaint()将安排UI线程调用正确的paint-methods。
  • The paint-method should then simply read the state of the model, and draw the component accordingly. 然后,paint-method应该简单地读取模型的状态,并相应地绘制组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM