JFrame到图像而不显示JFrame [英] JFrame to image without showing the 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 已设置code>的
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!