[英]Java MouseClicked Not Working When Run With awt Canvas
For a Java program, I need to detect the click of a mouse.对于 Java 程序,我需要检测鼠标的点击。 I imported import java.awt.event.*;
我导入import java.awt.event.*;
. . And ran this:并运行了这个:
public void mouseClicked(MouseEvent e)
{
if (e.getButton() == MouseEvent.BUTTON1)
{
System.out.println("Click position (X, Y): " + e.getX() + ", " + e.getY());
}
}
When this is run, I don't get any output when I click on the screen.当它运行时,当我点击屏幕时,我没有得到任何 output。
This is what the start of my class looks like:这是我的 class 开始的样子:
class Drawing extends Canvas implements MouseListener, MouseMotionListener{
I am not sure why this is happening.我不确定为什么会这样。 I am on mac and another post ( JAVA mouseClicked event doesnt get fired on the Mac ) suggests that there might be something wrong with using a mac.我在 mac 上,另一个帖子( JAVA mouseClicked 事件不会在 Mac 上触发)表明使用 mac 可能有问题。
As per https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html根据https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html
The listener needs to be added to a component eg a button, panel etc.侦听器需要添加到组件中,例如按钮、面板等。
public class MouseEventDemo implements MouseListener {
//where initialization occurs:
//Register for mouse events on blankArea and the panel.
blankArea.addMouseListener(this);
addMouseListener(this);
...
public void mouseClicked(MouseEvent e) {
System.out.println ("Mouse clicked (# of clicks: "
+ e.getClickCount() + ")", e);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.