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


基础教程推荐
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01