多线程的Java图形 [英] multithreading for java graphics
问题描述
我有一个Java应用程序可以传输原始数据并相应地绘制实时绘图。这是通过调用我写的使用Graphics对象的类的方法来处理的。我在重写的paintComponent方法中实现了算法,以生成最新数据的所有图。我在我的类中有其他方法来更新paintComponent方法中绘制图形所使用的变量。
在我的主类中,我定期更新定时器事件处理程序中的图形。在事件处理程序中,我调用更新某些变量的图表类中的方法,进行一些计算,然后调用repaint()(显然是调用paintComponent方法的正确方法)。
我的问题是,我在paintComponent方法中使用的算法可能需要(相对)很长时间才能完成,具体取决于我的图的数量和分辨率。 (我还没有完全遇到这个问题,但我试图解决它现在)。当然我不希望所有这些图形都占用我应用程序的所有处理时间,所以我想知道是否可以在单独的线程中执行paintComponent。
如果我在我的主体中创建一个子类以在单独的线程中运行并简单地称为我描述的图形方法,会发生什么情况?会自动使所有这些方法(包括paintComponent)在新线程中执行?或者我会不得不修改我的图形类本身为此工作?理想情况下,我想避免修改我的图表类,因为我已经将它设计为在NetBeans GUI构建器中作为JPanel工作,并且我想避免打破该功能。
您必须将paint方法重定向到 SwingWorker
或 Runnable#Thread
(所有输出到GUI必须包装到 invokeLater
),例如此处或
I have a java application that streams raw data and draws real time plots accordingly. this is handled by calling methods from a class i wrote that uses the Graphics object. i implemented algorithms in an overridden paintComponent method to generate all the plots from the most recent data. i have other methods in my class to update variables used in the paintComponent method to draw the graphs.
in my main class, i update my graphs periodically in a timer event handler. in the event handler i call methods from my graphs class that update certain variables, do a few calculations, and then call repaint() (which apparently is the correct way to call the paintComponent method).
my problem is, the algorithms i use in the paintComponent method can take a (relatively) long time to complete depending on the amount and resolution of my plots. (i haven't exactly run into this problem yet, but i'm trying to address it now). of course i wouldn't want all this graphing to hog all the processing time of my application, so i was wondering if it's possible to have "paintComponent" execute in a separate thread.
what would happen if i created a subclass in my main to run in a separate thread and simply called the graph methods i described? would that automatically make all of those methods (including paintComponent) execute in the new thread? or would i have to modify my graph class itself for this to work? ideally i would like to avoid modifying my graphs class because i have already designed it to work within the NetBeans GUI builder as a JPanel, and i'd like to avoid breaking that functionality.
you have to redirect paint methods to the SwingWorker
or Runnable#Thread
(all output to the GUI must be wrapped into invokeLater
), example here or here
这篇关于多线程的Java图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!