1
votes

I have a JPanel object called drawPanel. I draw various things like rectangles on it and when I try to create a bufferedimage and save it as following, it only saves a blank image with just the background color and not the rectangles drawn onto the frame.

BufferedImage image = createImage(drawPanel);
File outputfile = new File("MyImage.jpg");
try {
    ImageIO.write(image, "jpg", outputfile);
} catch (IOException e) {
     e.printStackTrace();
}



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

Kindly help me fix this problem.

2
For better help sooner, post an MCVE (Minimal Complete Verifiable Example) or SSCCE (Short, Self Contained, Correct Example).Andrew Thompson
Maybe using panel.paint(g) in addition to panel.print(g) will solve your problemAlex Coleman
@AlexColeman: I'd actually think that printAll(g) would be better -- if he wanted to draw child components too.Hovercraft Full Of Eels
@HovercraftFullOfEels That sounds like it might be better, don't have a compiler open so I'm just taking a stab at it so he can try :PAlex Coleman
How does drawPanel work?MadProgrammer

2 Answers

3
votes

This Graphics2D g2 = (Graphics2D) drawPanel.getGraphics(); is your problem. Calling print, printAll or paint will wipe clean anything that was painted to the component using getGraphics.

The short answer is, never use it. The long answer is, create a custom component, that extends from something like JPanel and override it's paintComponent method and perform ALL your custom painting within in it, when it's called.

See Painting in AWT and Swing and Performing Custom Painting for more details

2
votes

A little hackery with Robot

Simply replace your method createImage with my one. :-)

public BufferedImage createImage(JPanel panel) {
    //Get top-left coordinate of drawPanel w.r.t screen
    Point p = new Point(0, 0);
    SwingUtilities.convertPointToScreen(p, panel);

    //Get the region with wiht and heighht of panel and 
    // starting coordinates of p.x and p.y
    Rectangle region = panel.getBounds();
    region.x = p.x;
    region.y = p.y;
    
    //Get screen capture over the area of region
    BufferedImage bi = null;
    try {
        bi = new Robot().createScreenCapture( region );
    } catch (AWTException ex) {
        Logger.getLogger(MyPaintBrush.class.getName()).log(Level.SEVERE, null, ex);
    }
    
    return bi;
}

enter image description here

(Credit to this dude)