我正在处理一些代码,以便在容器(JPanel)周围拖动一个形状(当前是正方形)。我已经能够绘制一个蓝色方块,我的鼠标监听器正在工作,因为我可以拖动方块。但由于以下原因,它仍然没有按照我的意愿行事:
我只能对角拖动形状。换句话说,无论我在哪里移动鼠标,形状只会在屏幕上向上或向下移动。
我只能拖动一次形状。换句话说,如果我在形状内部单击,将其拖动到一个新位置,然后释放鼠标,那就是它 - 如果不重新启动程序,我就无法移动它。
以下是我的代码的相关(我希望!)部分:
DragPanel类声明(基本上是JPanel的扩展):
public class DragPanel extends JPanel implements MouseListener, MouseMotionListener
{
Graphics2D g2;
Rectangle2D square;
Color colour;
double x1, y1, x2, y2, size;
double offsetX, offsetY;
boolean dragging = false;
构造方法:
public DragPanel()
{
x1 = 10.0;
y1 = 10.0;
size = 40.0;
x2 = x1 + size;
y2 = y1 + size;
square = new Rectangle2D.Double(x1, y1, size, size);
colour = Color.BLUE;
setFocusable(true);
addMouseListener(this);
addMouseMotionListener(this);
this.requestFocus();
}
PaintComponent方法,以及MouseDragged,MousePressed,MouseReleased方法:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g2 = (Graphics2D) g;
g2.draw(square);
g2.setColor(colour);
g2.draw(square);
}
@Override
public void mouseDragged(MouseEvent ev)
{
if (dragging)
{
double mx = ev.getX();
double my = ev.getY();
x1 = mx - offsetX;
y1 = mx - offsetY;
square = new Rectangle2D.Double(x1, y1, size, size);
repaint();
}
}
@Override
public void mousePressed(MouseEvent ev)
{
double mx = ev.getX();
double my = ev.getY();
if (mx > x1 && mx < x2 && my > y1 && my < y2)
{
dragging = true;
offsetX = mx - x1;
offsetY = my - y1;
}
}
@Override
public void mouseReleased(MouseEvent arg0)
{
dragging = false;
}
答案 0 :(得分:1)
在mouseDragged()
中x1 = mx - offsetX;
y1 = mx - offsetY;
应该是
x1 = mx - offsetX;
y1 = my - offsetY;
x2 = x1 + size;
y2 = y1 + size;
每次移动时都需要更新正方形的所有边界。我没有将它们显式存储在实例变量中,而是使用内置的矩形2D方法,如getMinX()和getMaxX()
答案 1 :(得分:0)
好的,我让它上班了!我不得不补充道:
x2 = x1 + size;
y2 = y1 + size;
我的mouseDragged()方法如下:
@Override
public void mouseDragged(MouseEvent ev)
{
if (dragging)
{
double mx = ev.getX();
double my = ev.getY();
x1 = mx - offsetX;
y1 = my - offsetY;
x2 = x1 + size;
y2 = y1 + size;
square = new Rectangle2D.Double(x1, y1, size, size);
repaint();
}
}