[英]My mouse listeners don't seem to be working. Can someone help me? I have to move a ball to where my mouse is clicked and it is not working
This is the code but it is not working.这是代码,但它不起作用。 I thought i added the right thing but the mouse listener is even responding.
我以为我添加了正确的东西,但鼠标监听器甚至响应。 Much help is needed.
需要很多帮助。
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();
}
}
}
It is not working as you can see.如您所见,它不起作用。 I don't know what is wrong.
我不知道出了什么问题。
You are working with the java.awt.event.MouseEvent , right?
您正在使用java.awt.event.MouseEvent ,对吧?
The problem is, that you invoke methods on the MouseEvent e
that do not work like expected in your case.问题是,您在
MouseEvent e
上调用的方法在您的情况下不像预期的那样工作。 The Methods e.isMetaDown()
and e.isShiftDown()
check weather the Meta modfier or the Shift modifier is down on this event.方法
e.isMetaDown()
和e.isShiftDown()
检查 Meta 修改器或 Shift 修改器是否在此事件上关闭。 I think you searches for a method to check if you pressed the left ( MouseEvent.BUTTON1
) or right mouse button ( MouseEvent.BUTTON3
).我认为您搜索一种方法来检查您是否按下了鼠标左键(
MouseEvent.BUTTON1
)或鼠标右键( MouseEvent.BUTTON3
)。 You can consult this page:你可以参考这个页面:
https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/java/awt/event/MouseEvent.html https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/java/awt/event/MouseEvent.ZFC35FDC70D5FC69D2635883A822C7A
to inform yoursef about the Methods that can be invoked on MouseEvent
s.告知您可以在
MouseEvent
上调用的方法。
You could try these two small changes.你可以试试这两个小改动。 (But this code is not tested,.) If you want somebody to test the code, then please post a minimal reproducible example as @DontKnowMuchBut Getting Better already mentioned.
(但此代码未经测试。)如果您希望有人测试代码,请发布一个最小的可重现示例,如 @DontKnowMuchBut 已经提到的越来越好。
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();
}
}
}
I hope this is helpfull.我希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.