JFrame 到图像而不显示 JFrame [英] JFrame to image without showing the JFrame

查看:40
本文介绍了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;
}

但是,这仅在 JFramesetVisible(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆