The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

But it looks like it does not work . I have seen a code like this on a site, and there was said that it should save the content of my canvas to a .jpg file. Sadly, it creates a blank .jpg file. Is there something that i have to change at my code to make it work? Is there any other way that i can save the content of my paint ?

Re: Need help to save Canvas content to a file

What exactly do you mean when you say that it does not work? Do you get an exception? Some kind of strange behavior? What exactly happens versus what you expect to happen? If you posted an SSCCE that we could copy, paste, and run, it would be easier to help you out.

Re: Need help to save Canvas content to a file

I made a smaller program to make it easier to put here:
Here is a class which extends Canvas. Inside the method paint i draw a String. And, i add mouselisteners to make it possible to draw on the Canvas...using the mouse...just as with the pencil tool of the paint:

My problem is the following:
When i save the drawing to a file, i get a .jpg file on which i have drawn the String (the one that is drawn inside the paint() method of the Canvas class). But, if i draw a line using the mouse (using the "pencil" too), i only get the String saved to the file, and not what is drawn after. But i want my program to save all i draw ! What am i doing wrong ?

Re: Need help to save Canvas content to a file

Ah, I see. Don't call getGraphics() on a Component like that. Instead, store everything you need to draw in a Collection, and write a method that iterates through the Collection and draws each item. Then you can call that method from your paintComponent() method or from your save() method.