I am trying to serialize a Canvas
instance (using the Serializable
interface) on which I have painted some pixels like the following code suggests:
Canvas board = new Canvas();
Graphics g = board.getGraphics();
g.setColor(Color.BLACK);
g.drawString("txt", 10, 20);
g.dispose();
Then when I serialize board
it doesn't save the pixels I've painted. I'm guessing this is because by using getGraphics()
I am not saving those pixels to any instance, so I thought that perhaps I should instead paint from within the Canvas
's paint()
method. Would serializing the Canvas
then save the modified pixels too? If not, what are my options to save/serialize a Canvas
with the pixels I've modified? I am guessing I would have to serialize the Graphics
object instead of the Canvas
? I am new to Java graphics, any help will be greatly appreciated.
To be more clear, what I'm trying to do is have the pixels I've put on a Canvas
instance saved to a file using serialization. Then later I need to reload this Canvas
instance from the serialized file I saved earlier, so that when I use it on the screen I see the exact same pixels I modified just before I serialized the Canvas
. I know how to serialize objects and all that. I am just unclear where all the pixels are stored.
Update1:
The way the user draws something on the screen is by left-clicking on the Canvas
area. Then MouseListener
calls the following method, passing along the Point
object specifying the mouse xy:
private void drawAt(Point p)
{
Graphics g = board.getGraphics();
g.setColor(brushColor);
g.setFont(brushFont);
g.drawString(brushText, p.x, p.y);
g.dispose();
}