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.
panel.paint(g)
in addition topanel.print(g)
will solve your problem – Alex ColemanprintAll(g)
would be better -- if he wanted to draw child components too. – Hovercraft Full Of EelsdrawPanel
work? – MadProgrammer