My program draws numerous rectangles in a JPanel; the location, dimensions and colors are determined by a random number generator. I want to save the panel contents as a jpg. I believe this requires converting the panel contents to a buffered image using something like this:

BufferedImage awtImage = new BufferedImage(canvasPanelWidth,canvasPanelHeight,BufferedImage.TYPE_INT_RGB);  
Graphics2D g2 = awtImage.createGraphics();
canvasPanel.print(g2);

This apparently causes my paintComponent method to execute, which generates a new set of randome numbers and a completely new set of rectangles and associated jpg file.

Is there another way to save the JPanel as a jpg that will not cause a repaint or do I have to generate the rectangles directly in a buffered image and display in a JLabel as an imageIcon?

Thanks for any suggestions.

Instead of drawing directly to the panel's Graphics, create a new Image and draw to its Graphics. Then just copy that to the panel using drawImage and also save it as a jpeg

ps: Updating the random numbers inside paintComponent is a really bad idea. You have no direct control over when it is called, and it may be called when you don't expect, eg when the user re-sizes the window, or drags it onto a second monitor, or various other reasons that you have no access to.
You have to update them only when your program logic explicitly requires a new set of rectangles. That would also be the best time to create your own Image with those new rectangles, so your paintComponent just has to draw the latest Image to its own Graphics

Thank you. I'll implement as you have suggested.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.