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