简体   繁体   English

在多线程程序中摆动图形

[英]Swing graphics in multithreaded program

I'm coding a game; 我正在编写游戏; something like this: http://i.stack.imgur.com/HBrEE.png 像这样的东西: http : //i.stack.imgur.com/HBrEE.png

I have a class named Canvas which extends JLabel and in overriden paintComponent() , put an image of gridlines as background, then paint the player and obstacles (walls). 我有一个名为Canvas的类,该类扩展了JLabel并在重写的paintComponent() ,将网格线的图像作为背景,然后绘制玩家和障碍物(墙壁)。

By using createGraphics() , I get a Graphics2D object. 通过使用createGraphics() ,我得到了Graphics2D对象。 I need this to paint weapons and bullets from their classes, too. 我也需要用它来绘制他们班上的武器和子弹。 (As you see, there are several weapons that shoot bullets in specific time intervals.) (如您所见,有几种武器可以在特定的时间间隔内发射子弹。)

For implementing all these, using SwingUtilities.invokeLater() I paint the gridlines, player and walls in Canvas class. 为了实现所有这些功能,我使用SwingUtilities.invokeLater()在Canvas类中绘制了网格线,播放器和墙。 I thought of creating a thread per weapon and one per bullet; 我想为每个武器创建一个线程,为每个子弹创建一个线程。 I know, it's an overkill but since I'm new to multithreading I have no other ideas! 我知道,这太过分了,但是由于我是多线程的新手,所以我没有其他想法了!

And another problem is with Graphics2D object: I need to share this object between threads so I thought of using final keyword; 还有另一个问题是Graphics2D对象:我需要在线程之间共享该对象,所以我想到了使用final关键字; but it's not possible because the value of Graphics2D object will be determined in paintComponent() . 但是这是不可能的,因为Graphics2D对象的值将在paintComponent()确定。

Thanks in advance for any help you are able to provide. 在此先感谢您能提供的任何帮助。

You shouldn't use multi-threaded rendering threads ever (well, in 99% of the cases at least). 永远不要使用多线程渲染线程(至少在99%的情况下)。 Most graphics programs keep the full scene state in some object tree that only one thread renders every so often (1/60th of a second). 大多数图形程序将整个场景状态保存在某个对象树中,该对象树每隔一个频率(1/60秒)就会渲染一次。 The rendering thread goes through each object in the render tree and invoke .paint or whatever else will get the object to be drawn. 渲染线程遍历渲染树中的每个对象,然后调用.paint或其他将获取要绘制对象的对象。 Rinse and repeat and you're done. 冲洗并重复,就完成了。

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

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