对于Java程序,我需要检测鼠标的单击。我导入了import java.awt.event.*;
。并运行此:
public void mouseClicked(MouseEvent e)
{
if (e.getButton() == MouseEvent.BUTTON1)
{
System.out.println("Click position (X, Y): " + e.getX() + ", " + e.getY());
}
}
运行此命令时,单击屏幕时没有任何输出。
这是我的课程开始的样子:
class Drawing extends Canvas implements MouseListener, MouseMotionListener{
我不确定为什么会这样。我在Mac上,另一则帖子(JAVA mouseClicked event doesnt get fired on the Mac)建议使用Mac可能有问题。
根据https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html
侦听器需要添加到组件,例如按钮,面板等。
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);
}