难以理解Java MouseEvent

时间:2010-03-01 04:10:22

标签: java

我正在做这些iTunes Stanford课程,而且我一直在学习Java。事情进展顺利,但他们最近引入了事件 - 特别是MouseEvents。我一直在阅读本书中的章节,并通过示例代码,并且有些东西不适合我...它总是异步的东西给我带来麻烦:-D

早些时候,有些人提到重要的是我提到“addMouseListener”是Graphics导入中的一个类。据我所知,这只是在画布上添加了一个毯子鼠标监听器。

我仍然是新手,所以我可能不会像我应该那样描述事情。

这是我试图简化的一段代码,以便更好地理解它。目前,它将构建一个红色矩形,我可以单击它并沿x轴拖动它。大!!!

import java.awt.*;
import java.awt.event.*;
import acm.graphics.*;
import acm.program.*;

/** This class displays a mouse-draggable rectangle and oval */

public class DragObject extends GraphicsProgram {

    /* Build a rectangle  */
    public void run() {

        GRect rect = new GRect(100, 100, 150, 100);
        rect.setFilled(true);
        rect.setColor(Color.RED);
        add(rect);
        addMouseListeners();
    }

/** Called on mouse press to record the coordinates of the click */
    public void mousePressed(MouseEvent e) {
        lastX = e.getX();
        lastY = e.getY();
        gobj = getElementAt(lastX, lastY);
    }

/** Called on mouse drag to reposition the object */
    public void mouseDragged(MouseEvent e) { 

            if((lastX) > 100){
            gobj.move(e.getX() - lastX, 0);

            lastX = e.getX();
            lastY = e.getY();
        }
    }

/** Called on mouse click to move this object to the front */
    public void mouseClicked(MouseEvent e) {
        if (gobj != null) gobj.sendToFront();
    }

/* Instance variables */
private GObject gobj;   /* The object being dragged */
private double lastX;   /* The last mouse X position */
private double lastY;   /* The last mouse Y position */
}

如果我将鼠标拖离画布,我希望矩形保持在画布内,而不是移动它(如果你移动超出滚动区域仍然按下鼠标按钮,水平滚动条的行为相同点击)。我怎样才能做到这一点?

我一直在尝试这些方面的东西,但它不能正常工作:

    if  ( ( lastX > (getWidth() - PADDLE_WIDTH) ) || ( lastX < PADDLE_WIDTH ) ) {
        gobj.move(0, 0);
    } else {
        gobj.move(e.getX() - lastX, 0);
    }

2 个答案:

答案 0 :(得分:2)

您的代码正在相对于鼠标的最后位置移动矩形。当你只是移动东西时,这种方法很好,但是当你想要它停在边界时,你需要使用绝对定位。

// When the mouse is pressed, calculate the offset between the mouse and the rectangle
public void mousePressed(MouseEvent e) {
    lastX = e.getX();
    lastY = e.getY();
    gobj = getElementAt(lastX, lastY);
}

public void mouseDragged(MouseEvent e) { 
        double newX;

        // Assuming you can get the absolute X position of the object.
        newX = gobj.getX() + e.getX() - lastX;
        // Limit the range to fall within your canvas. Adjust for your paddle width as necessary.
        newX = Math.max( 0, Math.min( newX, getWidth() ) );
        // Set the new position of the paddle, assuming you can set the absolute position.
        gobj.setX( newX );

        lastX = e.getX();
        lastY = e.getY();
    }
}

这可能不是你想要的,因为一旦离开边缘,物体就会停止移动,但是一旦你向画布移回,你的桨就会立即移动而不是等待鼠标到达与它开始的桨叶相同的相对位置。

你可以尝试让它做你想做的事。

答案 1 :(得分:0)

为了做到这一点,你需要知道Canvas对象的宽度,我确信会有一个提供这个值的方法。然后,您可以根据画布的宽度检查MouseEvent的当前x位置,并在超过画布宽度时不增加形状对象的x坐标。根据要在画布中保留多少形状,您可能还需要考虑形状对象的宽度。

在gui中处理w /动画和移动物体时,有一件事可以帮助我在纸上绘制一些场景,并注意坐标如何变化。

相关问题