Draw a triangle using mouse drag (how can I move the previous drawn triangle using mouse drag)

橙三吉。 提交于 2019-12-25 04:49:15

问题


How to move a triangle to a new location using mouse drag (which was previous drawn using mouse drag)?

...
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() {

/* I dont know how to move (drag) the whole triangle to new location and later delete the previous drawn triangle. The mouseDragged method only draw a new triangle using mouse drag :-( */

    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

回答1:


when you start to drag you have to detect if your current mouse location is on one of the existing Polygons, also mark the starting location

When it is you dont add a new polygon, but you add the amount moved to the different points of the existing polygon and repaint



来源:https://stackoverflow.com/questions/1485367/draw-a-triangle-using-mouse-drag-how-can-i-move-the-previous-drawn-triangle-usi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!