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();
相关文章