mad max
mad max

Reputation: 61

free hand drawing in java using class Point

I am trying to write a simple free hand drawing code in java using Point class and arraylist but i am getting stuck. Firstly, cant really leave the origin point, and secondly ther's always a line drawn between the 2 points even when mouse is not dragged.

public class FreeDraw extends Applet implements MouseMotionListener
{
     int x,y,m,n;
     ArrayList<Point> al;
     public void init()
     {
         al = new ArrayList<>();

        this.addMouseMotionListener(this);

     }
      public void paint(Graphics g)
      {

          for(int i=0;i<al.size();i++)
          {
               m=al.get(i).x;
               n=al.get(i).y;

               g.drawLine(m,n,x,y);  

               x=m;
               y=n;

          }
      }
     public void mouseDragged(MouseEvent e)
     {
        al.add(new Point(e.getX(),e.getY()));
        repaint(); 
     }


    public void mouseMoved(MouseEvent e)
    {
    //do nothing
    }

}

Upvotes: 2

Views: 1047

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

You need to seed the initial x/y position (otherwise m and n will be 0x0 to the first point)

Something like...

@Override
public void paint(Graphics g) {
    super.paint(g);
    if (!al.isEmpty()) {
        int x = al.get(0).x;
        int y = al.get(0).y;
        for (int i = 1; i < al.size(); i++) {
            m = al.get(i).x;
            n = al.get(i).y;

            g.drawLine(m, n, x, y);

            x = m;
            y = n;

        }
    }
}

for example.

Apart from the fact that Applet was replaced with JApplet some 16 years ago, the applet plugin is no longer supported by Oracle, but most of the browsers actively block it, making it a dead end technology.

See Java Plugin support deprecated and Moving to a Plugin-Free Web for more details

Upvotes: 1

Related Questions