简体   繁体   English

MouseDrag绘制一个正方形无法正常工作

[英]MouseDrag drawing a Square not working as intended

 @Override
    public Shape getShape() {
        final Rectangle2D.Double result = new Rectangle2D.Double();
        result.setFrameFromDiagonal(getStart(), getEnd());
        //FIX this is causing square to move when going opposite direction  
        result.setRect(result.getX(), result.getY(),
                       result.getHeight(), result.getHeight());
        return result;
    }

So here is my code that is drawing a square using Rectangle2D.Double. 所以这是我的代码,使用Rectangle2D.Double绘制正方形。 The getStart() and getEnd() are points that are being returned from mouseDrag events. getStart()和getEnd()是从mouseDrag事件返回的点。 When I drag to the right or up, it works as intended and creates a square. 当我向右或向上拖动时,它会按预期工作并创建一个正方形。 When I drag left or down the square moves with the drag as it draws. 当我向左或向下拖动时,正方形随着拖动而移动。 I am fairly new to Java swing and paint components. 我对Java swing和paint组件还很陌生。 Wondering if anyone know what is causing this and why? 想知道是否有人造成了这种情况,为什么?

You need to consider a few specialities: 您需要考虑一些特长:

  1. Save the first coordinate on mouse click: x,y 单击鼠标保存第一个坐标:x,y
  2. Save the last coordinate on mouse drag x2,y2 在鼠标拖动x2,y2上保存最后一个坐标
  3. Set min x and y coordinates as the startpoint for setRect: Math.min(x,x2); 将最小x和y坐标设置为setRect的起点:Math.min(x,x2);
  4. Use the absolute value of the coordinate difference to calculate the height and width of rectangle: Math.abs(x-x2); 使用坐标差的绝对值来计算矩形的高度和宽度:Math.abs(x-x2);

px = Math.min(x,x2);
int py = Math.min(y,y2);
int pw=Math.abs(x-x2);
int ph=Math.abs(y-y2);
result.setRect(px, py, pw, ph);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM