0

我必须在 JFRame 中用鼠标画线。这是我的方法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);
 }
}

这是基于我从接口 MouseMotionListener 和 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();
  }
 }

这个想法是收集点,然后在它们之间画线,这样我得到一条曲线而不是直线。你能帮我找出我正在做的逻辑错误吗?

谢谢!

4

1 回答 1

1

您将超过集合的结尾。

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();
  }

}

于 2012-11-01T19:29:08.603 回答