使用awt Canvas运行时,Java MouseClicked无法正常工作

对于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可能有问题。

wsf945162 回答:使用awt Canvas运行时,Java MouseClicked无法正常工作

按照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);
}
本文链接:https://www.f2er.com/3155668.html

大家都在问