JFrame to image without showing the JFrame

我的梦境 提交于 2019-12-01 06:18:06

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

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