JFrame to image without showing the JFrame

后端 未结 2 1793
天命终不由人
天命终不由人 2021-01-13 22:13

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:

2条回答
  •  时光取名叫无心
    2021-01-13 23:10

    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
    

提交回复
热议问题