在jPanel周围拖动/移动形状 [英] Drag/Moving a shape around jPanel

查看:200
本文介绍了在jPanel周围拖动/移动形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天我问了一个问题,关于如何绘制一个边框来保持一个形状,如何拖放所选择的形状

Yesterday I ask a question about how to draw a bounding box to hold a shape inside and how to drag and drop that selected shape.

第一个问题已经解决。但我在移动形状方面遇到了一些麻烦。是否有任何特定的转换来移动jPanel周围的形状?

The first question is solved. But I'm having some trouble to move the shape. Is there any especific transformations to move a shape around the jPanel?

我有这样的代码:

public boolean drag(MouseEvent e) {
    if(points.isEmpty()) //if point's vector is empty
        return false;

    if(!selected)
        return false;

    int x = e.getX(), y = e.getX();

    if (!dragging)
        lastMovePoint.setLocation(x, y);

    dragging = true;

    int deslocX = 0;
    int deslocY = 0;

    int oldX = -1;
    int oldY = -1;

    int size = points.size();
    for(int i = 0; i < size; i++) {
        oldX = lastMovePoint.x;
        oldY = lastMovePoint.y;

        deslocX = x - oldX;
        deslocY = y - oldY;

        points.set(i, new Point(points.get(i).x + deslocX, points.get(i).y + deslocY));
//set the vector of points so that when there is a repaint() it repaints the shape with the new
//coordinates


    }
     lastMovePoint.setLocation(x, y); //set the location of the old point
    return true;
}

此方法由监听器mouseDragged调用,并在成功时返回true。我想要做的是添加前一个dragg和实际之间的差异。

This method is called by the listener mouseDragged and return true in case of sucess. What I'm trying to do is to add the difference between the previous point of dragg and the actual.

当我运行此代码时遇到问题:

When I run this code I have a problem:

形状只向右/向左,向上和下来不起作用...

The shape only goes to right/left, up and down is not working...

推荐答案

int x = e.getX(), y = e.getX();

这应该改为

int x = e.getX(), y = e.getY();

这就是为什么它只能在x方向工作,你实际上并没有考虑到Y方向

That's why it only works in the x direction, you aren't actually taking into account the Y direction

这篇关于在jPanel周围拖动/移动形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆