JFrame to image without showing the JFrame(JFrame 到图像而不显示 JFrame)
问题描述
我正在尝试将 JFrame 渲染到图像而不显示 JFrame 本身(类似于 this 问题正在询问).我试过使用这段代码:
I am trying to render a JFrame to an image without ever displaying the JFrame itself (similar to what this question is asking). I have tried using this piece of code:
private static BufferedImage getScreenShot(Component component)
{
BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_RGB);
// call the Component's paint method, using
// the Graphics object of the image.
component.paint(image.getGraphics());
return image;
}
但是,这仅在 JFrame
的 setVisible(true)
设置时有效.这将导致图像显示在屏幕上,这不是我想要的.我也尝试过创建类似的东西:
However, this only works when the JFrame
's setVisible(true)
is set. This will cause the image to be displayed on the screen which is not something I want. I have also tried to create something like so:
public class MyFrame extends JFrame
{
private BufferedImage bi;
public MyFrame(String name, BufferedImage bi)
{
this.bi = bi;
super(name);
}
@Override
public void paint(Graphics g)
{
g.drawImage(this.bufferedImage, 0, 0, null);
}
}
然而,这会显示黑色图像(如上面的代码).我很确定我所追求的是可能的,问题是我真的找不到方法.我在自定义 Swing 组件方面的经验非常有限,因此我们将不胜感激.
This however displays black images (like the code above). I am pretty sure that what I am after is possible, the problem is that I can't really find how. My experience with custom Swing components is pretty limited, so any information will be appreciated.
谢谢.
推荐答案
这是一个可以解决问题的片段:
Here is a snippet that should do the trick:
Component c; // the component you would like to print to a BufferedImage
JFrame frame = new JFrame();
frame.setBackground(Color.WHITE);
frame.setUndecorated(true);
frame.getContentPane().add(c);
frame.pack();
BufferedImage bi = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = bi.createGraphics();
c.print(graphics);
graphics.dispose();
frame.dispose();
这篇关于JFrame 到图像而不显示 JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JFrame 到图像而不显示 JFrame
- 未找到/usr/local/lib 中的库 2022-01-01
- 转换 ldap 日期 2022-01-01
- 获取数字的最后一位 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01