JFrame to image without showing the JFrame

心不动则不痛 提交于 2019-12-01 06:03:15

问题


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;
}

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);
    }
}

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.

Thanks.


回答1:


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();



回答2:


This method might do the trick:

public BufferedImage getImage(Component c) {
    BufferedImage bi = null;
    try {
        bi = new BufferedImage(c.getWidth(),c.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d =bi.createGraphics();
        c.print(g2d);
        g2d.dispose();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return bi;
}

you'd then do something like:

JFrame frame=...;
...
BufferedImage bImg=new ClassName().getImage(frame);
//bImg is now a screen shot of your frame


来源:https://stackoverflow.com/questions/12477522/jframe-to-image-without-showing-the-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!