[英]Java draw to Graphics in own thread, outside EDT?
我正在编写一个 Swing 应用程序,它使用 Apache PDFBox 在paintComponent 方法中将PDF 页面绘制到JPanel 的Graphics2D 对象。 绘图需要一段时间,因此当我的应用程序需要同时显示多个 PDF 页面时,它会变得缓慢且滞后。 我知道,由于我绘制 PDF 页面的 JPanel 是 GUI 的一部分,因此需要在事件调度线程中绘制它。 但是绝对不可能在自己的线程中绘制每个 JPanel 吗? 喜欢使用 SwingWorker 左右吗?
示例代码(简化):
public class PDFPanel extends JPanel {
@Override
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Graphics2D g2 = (Graphics2D) graphics;
int scale = 1; // (simplified this line)
g2.setColor(getBackground());
g2.fillRect(0, 0, getWidth(), getHeight());
try {
pdfRenderer.renderPageToGraphics(pageNumber, g2, (float) scale, (float) scale);
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用BufferedImage
图像字段。 它有一个createGraphics()
方法,您可以在其中进行绘制。 然后调用Graphics.dispose()
来清理资源。
然后在paintComponent
检查图像的可用性,以显示它。
渲染可以在 Future、SwingWorker 或其他任何东西中完成。 你是对的,不应该在paintComponent
进行繁重的操作,特别是因为它可能会被重复调用。
更好地在构造函数或控制器中启动渲染。
BufferedImage image = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
try {
pdfRenderer.renderPageToGraphics(pageNumber, g2, (float) scale, (float) scale);
} finally {
g2d.dispose();
}
最初宽度和高度没有填充,所以最好使用 PDF 中的宽度和高度。 也不是 Graphics2D 允许缩放; 您可以轻松添加缩放功能。
如何以原子方式处理传递渲染图像可能很清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.