【发布时间】:2010-03-02 13:51:23
【问题描述】:
我正在上这些 iTunes 斯坦福课程,并且我一直在学习 Java 入门。事情进展顺利,但他们最近引入了事件,特别是 MouseEvents。我一直在阅读书中的章节,并仔细阅读示例代码,但有些东西对我来说并不正确……总是那些异步的东西给我带来了麻烦:-D
之前,有些人提到我提到“addMouseListener”是图形导入中的一个类很重要。据我所知,这只是在画布上添加了一个毯子鼠标侦听器。
我对此仍然很陌生,所以我可能没有像我应该的那样描述事情。
这是我一直在尝试简化的一段代码,以便更好地理解它。目前,它将构建一个红色矩形,我可以单击它并沿 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);
}
【问题讨论】:
标签: java