Java 我的鼠标侦听器不';我好像不工作。有人能帮我吗?我必须移动一个球到我的鼠标被点击的地方,但它不工作
这是代码,但它不起作用。我以为我添加了正确的东西,但鼠标侦听器甚至在响应。需要很多帮助Java 我的鼠标侦听器不';我好像不工作。有人能帮我吗?我必须移动一个球到我的鼠标被点击的地方,但它不工作,java,swing,mouselistener,Java,Swing,Mouselistener,这是代码,但它不起作用。我以为我添加了正确的东西,但鼠标侦听器甚至在响应。需要很多帮助 class Mouse implements MouseListener { /** * Moves the ball to the (x, y) location where the mouse has been clicked */ public void mousePressed(MouseEvent e) { ball.setX(e.getX());
class Mouse implements MouseListener {
/**
* Moves the ball to the (x, y) location where the mouse has been clicked
*/
public void mousePressed(MouseEvent e) {
ball.setX(e.getX());
ball.setY(e.getY());
if (e.isMetaDown()) {
ball.move(getX(), getY());
repaint();
}
if (e.isShiftDown()) {
ball.setRandomSpeed(20);
ball.setLocation(Math.random(), Math.random());
repaint();
}
}
}
正如你所看到的,它不起作用。我不知道出了什么问题。您正在使用java.awt.event.MouseEvent,对吗
问题是,您在MouseEvent e
上调用的方法与您的案例中预期的不一样。方法e.isMetaDown()
和e.isShiftDown()
检查元修改器或移位修改器是否在此事件中关闭。我认为您正在搜索一种方法来检查是否按下了鼠标左键(MouseEvent.BUTTON1
)或鼠标右键(MouseEvent.BUTTON3
)。您可以查阅此页面:
通知您的SEF可以在MouseEvent
s上调用的方法
你可以试试这两个小变化。(但是这段代码没有经过测试!!)如果你想让别人测试代码,那么请发布一个最小的可重复的例子@DontKnowMuchBut Getting Better已经提到过了
class Mouse implements MouseListener {
/**
* Moves the ball to the (x, y) location where the mouse has been clicked
*/
public void mousePressed(MouseEvent e) {
ball.setX(e.getX());
ball.setY(e.getY());
if (e.getButton().equals(MouseEvent.BUTTON1)) {
ball.move(getX(), getY());
repaint();
}
if (e.getButton().equals(MouseEvent.BUTTON2)) {
ball.setRandomSpeed(20);
ball.setLocation(Math.random(), Math.random());
repaint();
}
}
}
我希望这是有帮助的。您是否将该类注册为侦听器?addMouseListener(new Mouse())您可能希望在您的问题中发布程序代码帖子,以便我们可以运行代码并亲自体验问题。非常感谢!这真的很有帮助!(1-)MouseeEvent扩展InputEvent。isMetaDown()和IsShift Down()方法是在InputEvent中定义的。您完全正确@camickr。看来我忽略了这一点。所以我改进了我的答案。