我想根据鼠标的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;
}
}
运行代码后,由于x和y初始化为这些值,因此将图像绘制在窗口的0、0坐标处。在屏幕周围单击不会移动图像,但是会正确更新存储在对象中的x和y。在测试过程中的某一时刻,图像确实移到了屏幕上的其他位置。但是,这发生在我没有单击窗口并且此后无法复制它时。我不确定它何时或如何移动。谢谢,
答案 0 :(得分:0)
将p.repaint();
添加到您的mousePressed
方法中。
这将导致面板重新绘制。
但是,仅执行此操作只会将另一个Image添加到图形组件中。
如果您不想将图像保持在先前的位置,
在super.paintComponent(a);
方法的开头添加一个paintComponent
以使面板处于空白状态。< / p>
JPanel p = new JPanel() {
protected void paintComponent(Graphics a){
super.paintComponent(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);
p.repaint();
}
});
答案 1 :(得分:0)
更改了此内容:
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);
}
});
为此:
p.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int xMouse = e.getX();
int yMouse = e.getY();
obj.changeX(xMouse);
obj.changeY(yMouse);
p.repaint();
System.out.println(xMouse+" "+yMouse);
}
});