【发布时间】:2019-12-03 03:11:55
【问题描述】:
我想根据鼠标的 x 和 y 位置在屏幕上移动图像。每次单击鼠标时,图像都应移动到该位置。
public class testSquare {
public static void main(String[] args) throws Exception {
//...
//object that stores x and y of mouse click
testSquareInfo obj = new testSquareInfo(0, 0);
//...
//panel that draws image, seems to only execute once
JPanel p = new JPanel ()
{
protected void paintComponent(Graphics a){
int x = obj.getXPos();
int y = obj.getYPos();
a.drawImage(img, x, y, 50, 50, null);
}
};
//listens for mouse click and sends x and y to object
p.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int xMouse = e.getX();
int yMouse = e.getY();
obj.changeX(xMouse);
obj.changeY(yMouse);
System.out.println(xMouse+" "+yMouse);
}
});
window.add(p);
window.setVisible(true);
}
}
//Second Class
public class testSquareInfo
{
private int x, y;
public testSquareInfo(int x, int y)
{
this.x = x;
this.y = y;
}
public void changeX(int xNew)
{
x = xNew;
}
public void changeY(int yNew)
{
y = yNew;
}
public int getXPos()
{
return x;
}
public int getYPos()
{
return y;
}
}
运行代码时,图像会在窗口的 0, 0, 坐标处绘制,因为 x 和 y 已初始化为这些值。在屏幕上单击不会移动图像,但会正确更新对象中存储的 x 和 y。在测试期间的某一时刻,图像确实移动到了屏幕上的不同位置。然而,这发生在我没有点击窗口的时候,并且从那以后我就无法复制它。我不确定它何时或如何移动。谢谢,
【问题讨论】:
-
您是否尝试过重新验证面板,如stackoverflow.com/questions/4392722/…所示
-
可能重复 Java: Move image towards mouse position 和 [将图像移动到在 JFrame 上单击的光标位置](stackoverflow.com/questions/43603615/…)
标签: java swing jpanel paintcomponent mouselistener