Convert JPanel to image

2020-01-29 09:35发布

问题:

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

thanks,

Jeff

回答1:

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.



回答2:

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


回答3:

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


回答4:

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