Convert JPanel to image

妖精的绣舞 提交于 2019-12-17 12:44:21

问题


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.



来源:https://stackoverflow.com/questions/1349220/convert-jpanel-to-image

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