2009-09-28 88 views
0

如何使用鼠标拖动(先前使用鼠标拖动绘制)将三角形移动到新位置?使用鼠标拖动绘制三角形(如何使用鼠标拖动来移动上一个绘制的三角形)

... 
java.util.List<Polygon> triangles = new LinkedList<Polygon>(); 
Point startDrag, endDrag, midPoint; 
Polygon triangle; 
... 
public PaintSurface() {  
    this.addMouseListener(new MouseAdapter() { 
    public void mousePressed(MouseEvent e) { 
    startDrag = new Point(e.getX(), e.getY()); 
    endDrag = startDrag; 
    repaint(); 
    }//end mousePressed 

public void mouseReleased(MouseEvent e) { 
... 
    int[] xs = { startDrag.x, endDrag.x, midPoint.x }; 
    int[] ys = { startDrag.y, startDrag.y, midPoint.y };  
    triangles.add(new Polygon(xs, ys,3));      
    startDrag = null; 
    endDrag = null; 
    repaint(); 
}//end mouseReleased 
... 


});//end addMouseListener 

    this.addMouseMotionListener(new MouseMotionAdapter() { 

/*我不知道如何移动(拖)整个三角形新的位置,之后再删除以前绘制三角形。该方法的mouseDragged仅使用鼠标拖动画出一个新的三角形:-( */

public void mouseDragged(MouseEvent e) { 
     endDrag = new Point(e.getX(), e.getY()); 
     repaint(); 
    }//end mouseDragged 
     }//end paintSurface  

     //Draw triangles 
     public void paint(Graphics g) { 
      Graphics2D g2 = (Graphics2D) g; 
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 

      //draw the thickness of the line 
      g2.setStroke(new BasicStroke(1)); 
      g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.00f));   
      g2.setPaint(Color.black);//set the triangle color 
      for (Polygon triangle : triangles) g2.drawPolygon(triangle); 
      if (startDrag != null && endDrag != null) { 
       g2.setPaint(Color.red); 
       g2.drawPolygon(triangle); 
      } 
      }//end paint  

       }//end private class PaintSurface 

回答

2
当你开始拖动你必须检测,如果你的当前鼠标位置是在现有的多边形的一个

,也标志着起点位置

当它是你不添加一个新的多边形,而且添加量转移到已有的多边形的不同点和重绘

+0

“量移”是它新的意义呢? – Jessy 2009-09-28 22:38:37

+0

未见其之间的不同拖动的起点和拖动的终点 说你拖动从5,10到15,25你已经移动了10和15,所以你给所有y的三角形15的所有x增加了10 – Peter 2009-09-29 05:32:46