0

I have to draw lines by mouse in a JFRame. Here is my method paintComponent:

public void paintComponent(Graphics g){
 Graphics2D g2d = (Graphics2D) g;
 if(pointCollection.get(0)!=null && pointCollection.get(pointCollection.size())!=null){
  g2d.setPaint(Color.BLUE);
  g2d.setStroke(new BasicStroke(1.5f));
  g2d.draw(line2d);
 }
}

which is based on my implemented methods I have from the interfaces MouseMotionListener and MouseListener.

public void mouseDragged(MouseEvent arg0) {

pointCollection = new ArrayList<Point>(50);
pointCollection.add(arg0.getPoint());
  for (int index = 0; index < pointCollection.size(); index++){
    line2d=new Line2D.Double(pointCollection.get(index), pointCollection.get(index+1));
   //repaint();
  }
 }

The idea is to colect points and than draw lines inbetween them, so that I get a curved line and not a straight one. Can you help me find out the logical mistake I am doing?

Thank you!

1 Answers1

1

You're going past the end of the collection.

public void mouseDragged(MouseEvent arg0) {

  for (int index = 0; index < (pointCollection.size() - 1); index++){
    line2d=new Line2D.Double(pointCollection.get(index), 
        pointCollection.get(index + 1));
   //repaint();
  }

}

Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111