views:

1271

answers:

3

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

thanks,

Jeff

+4  A: 

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

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

Tom
nice, thanks. is there a way i can figure out what the panel size should be (maybe its preferred size)?
Jeff Storey
I believe it's preferred size, or current size, as long as it has been rendered already. There are problems if it has not been rendered already - I cannot remember the exact specifics, but I remember running into similar properties when implementing a printing system.
aperkins
Yep, the preferred size works, but as you said, it doesn't render if the panel isn't displayed yet, which doesn't really help me too much. Is there a way to "render" it but not display it on the screen? Basically I'm building a component that needs to get written to an image but not displayed.
Jeff Storey
If you use panel.printAll(g) then it should work.
Russ Hayward
Hmm..that printAll still doesn't work if the component hasn't been made visible yet.
Jeff Storey
A: 

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.

camickr
A: 

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

Rastislav Komara