1

I have a class that extends a panel on which I have drawn some lines with

((Graphics2D) getGraphics).drawLine(x, y, x, y);

The lines are drawn correctly on the panel but when I run the following code to save an image (which I found on the internet) I save the panel without the lines

/**
 * Save the Panel as image with the name and the type in parameters
 *
 * @param name name of the file
 * @param type type of the file
 */
public void saveImage(String name,String type) {
    BufferedImage image = new BufferedImage(getWidth(),getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    paint(g2);
    try{
        ImageIO.write(image, type, new File(name+"."+type));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Javissimo
  • 25
  • 3
  • It's only going to get what the paint method paints. You should painting by overriding `paint` (or `paintComponent`, for Swing) rather than using `getGraphics`. See: https://stackoverflow.com/a/15991175/636009 – David Conrad Mar 13 '19 at 17:20
  • Possible duplicate of [Drawing an object using getGraphics() without extending JFrame](https://stackoverflow.com/questions/15986677/drawing-an-object-using-getgraphics-without-extending-jframe) – David Conrad Mar 13 '19 at 17:20
  • I created the java project with Netbeans and if I call it revalidate and repaint like in the example it gives me an error, because some components that I call have not yet been created. – Javissimo Mar 13 '19 at 20:54
  • What if you just move the painting into the paint method? – David Conrad Mar 14 '19 at 00:02
  • what do you mean? – Javissimo Mar 14 '19 at 13:00
  • No revalidate, no repaint, just override the paint method of your component, and draw the lines there, instead of calling getGraphics. You're already passing the Graphics2D object into the paint method. That's where the painting should take place. – David Conrad Mar 14 '19 at 15:30

0 Answers0