Search code examples
javaswingarraylistpolyline

drawPolyline() does not paint correctly


I implement a program that creates polyline dynamically using mouse clicks. Each mouse click adds new Point in an ArrayList and draw it all. if I click same Point it returns same value and add it to list but it draws new line to 0, 0. I wonder what is reason.

private ArrayList<Point> liste;

public void paintComponent (Graphics page)
{
    super.paintComponent(page);

    int xn[] = new int[liste.size()];
    int yn[] = new int[liste.size()];
    for(Point pot : liste){
        int ab = liste.indexOf(pot);
        xn[ab] = pot.x;
        yn[ab] = pot.y;

    }
    page.setColor (Color.red);

    page.drawPolyline(xn, yn, xn.length);
}

public void mousePressed(MouseEvent arg0) {
    liste.add(arg0.getPoint());
    repaint();
    System.out.println(arg0.getPoint());

}

http://i.hizliresim.com/r9YgkM.png


Solution

  • It is because you use indexOf to find the index in the array.

    Because of the way Point implements equals(Object), if you have clicked exactly the same point, indexOf will return the index of the first matching Point, not the second (or subsequent) occurrence. As such, the array elements corresponding to the second (or subsequent) occurrences will remain at their default value, zero.

    Instead, just declare ab outside the loop, and increment inside the loop:

    int ab = 0;
    for(Point pot : liste){
        xn[ab] = pot.x;
        yn[ab] = pot.y;
        ++ab;
    }