Convert JPanel to image

前端 未结 4 2010
盖世英雄少女心
盖世英雄少女心 2020-12-03 17:12

Is there a way to convert a JPanel (that has not yet been displayed) to a BufferedImage?

thanks,

Jeff

相关标签:
4条回答
  • 2020-12-03 17:38

    Take a look at BasicTableUI. The cell renderer is drawn on image without showing and then drawn on visible table component.

    0 讨论(0)
  • 2020-12-03 17:49

    The answer from Tom is basically correct, but invoke paint() directly is not recommended, as it is a synchronous call and can interrupt with other operation on the swing thread. Instead of using paint(), we should use print() instead

    public BufferedImage createImage(JPanel panel) {
    
        int w = panel.getWidth();
        int h = panel.getHeight();
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        panel.print(g);
        g.dispose();
        return bi;
    }
    
    0 讨论(0)
  • 2020-12-03 17:52

    Basically I'm building a component that needs to get written to an image but not displayed

    ScreenImage explains how to do what you want.


    Relevant section of ScreenImage.java (slightly edited). layoutComponent forces all buttons appear in the image.

    /**
     * @return Renders argument onto a new BufferedImage
     */
    public BufferedImage createImage(JPanel panel, int width, int height) {
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = bi.createGraphics();
        panel.setSize(width, height); // or panel.getPreferedSize()
        layoutComponent(panel);
        panel.print(g);
        g.dispose();
        return bi;
    }
    
    private void layoutComponent(Component component) {
        synchronized (component.getTreeLock()) {
            component.doLayout();
    
            if (component instanceof Container) {
                for (Component child : ((Container) component).getComponents()) {
                    layoutComponent(child);
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-03 18:03

    From the BufferedImage you can create a graphics object, which you can use to call paint on the JPanel, something like:

    public BufferedImage createImage(JPanel panel) {
    
        int w = panel.getWidth();
        int h = panel.getHeight();
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        panel.paint(g);
        g.dispose();
        return bi;
    }
    

    You may need to make sure you set the size of the panel first.

    0 讨论(0)
提交回复
热议问题