title: Drawing lines with mouse on canvas : Java awt
body: <p>The attempt is to enable drawing of figures(a line for now) with mouse on the awt canvas . Iam trying out java graphics for the first time . So not sure how to go about it . This is my first attempt :</p>
  
  <pre><code>package def.grafi;
  
  import java.awt.Canvas;
  import java.awt.Frame;
  import java.awt.Graphics;
  import java.awt.event.MouseAdapter;
  import java.awt.event.MouseEvent;
  import java.awt.image.BufferedImage;
  import java.io.File;
  import java.io.IOException;
  
  import javax.imageio.ImageIO;
  
    public class Dra {
    Frame f = new Frame();
  
  public void disp() {
      f.setBounds(100, 100, 200, 200);
      MosL ml = new MosL();
      Can c = new Can();
      f.add(c);
      c.addMouseListener(ml);
      c.addMouseMotionListener(ml);
      f.setVisible(true);
  }
  
  public static void main(String[] args) {
      Dra d = new Dra();
      d.disp();
  }
  
  public class MosL extends MouseAdapter {
      int sx = 0;
      int sy = 0;
      boolean onDrag = false;
  
      @Override
      public void mouseDragged(MouseEvent e) {
          if (onDrag) {
              int x = e.getX();
              int y = e.getY();
  
              Canvas comp = (Canvas) e.getSource();
              Graphics g = comp.getGraphics();
                              // comp.repaint(); &lt;&lt; for cleaning up the intermediate lines : doesnt work :(
              g.drawLine(sx, sy, x, y);
              return;
          }
          onDrag = true;
          sx = e.getX();
          sy = e.getY();
  
          System.out.println("Draggg");
      }
  
      @Override
      public void mousePressed(MouseEvent e) {
          System.out.println("Pressed");
      }
  
      @Override
      public void mouseReleased(MouseEvent e) {
          System.out.println("Released");
          if (onDrag)
              onDrag = false;
      }
  }
  
  public class Can extends Canvas {
      @Override
      public void paint(Graphics g) {
  
      }
  }
  }
  </code></pre>
  
  <p>Problems : 
  1) When the windows is minimized and restored , the drawn line is gone (due to repaint)
  2) What i want is the line should follow the mouse (when it is dragged) . the final line should extend from the point of pressing to the point of release of the mouse . Rite now , when the mouse moves , new lines are getting drawn . I am not sure how to clean up the intermediate lines from the canvas . </p>
  
  <p>Can someone help me out on these problems ? </p>