我在向左和向上绘制矩形时遇到问题。它们向右和向下画得很完美。 答案将受到高度赞赏。
import acm.program.*;
import acm.graphics.*;
import java.awt.event.*;
public class Ch10_Ex04_Mouse_Dragged_Rectangle extends GraphicsProgram
{
public void init()
{
addMouseListeners();
}
public void mousePressed (MouseEvent e)
{
X = e.getX();
Y = e.getY();
rect = new GRect (e.getX(), e.getY(), 0, 0);
add (rect);
}
public void mouseDragged (MouseEvent e)
{
// if (e.getX() < X)
// rect.setBounds(X, Y, -e.getX() + X, e.getY() - Y);
rect.setBounds(X, Y, e.getX()-X, e.getY()-Y);
}
int X, Y;
private GRect rect;
}
答案 0 :(得分:0)
我在这里做了一些假设,但我认为这是你正在寻找的mouseDragged函数(我没有对语法错误进行验证)。这应该在所有四个可能的拖动方向上绘制矩形(1)向右/向下,(2)向右/向上,(3)向左/向下,(4)向左/向上:
public void mouseDragged (MouseEvent e)
{
// Determine x-val and length
int xPos = X;
int xLen = Math.abs(X - e.getX());
if (e.getX() < X) {
xPos = e.getX();
}
// Determine y-val and length
int yPos = Y;
int yLen = Math.abs(Y - e.getY());
if (e.getY() < Y) {
yPos = e.getY();
}
// Set bounds on rectangle
rect.setBounds(xPos, yPos, xLen, yLen);
}