JFrame to image without showing the JFrame

后端 未结 2 1776
天命终不由人
天命终不由人 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:11

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

提交回复
热议问题