【问题标题】:Java MouseClicked Not Working When Run With awt Canvas使用 awt Canvas 运行时 Java MouseClicked 不起作用
【发布时间】:2020-03-02 09:57:59
【问题描述】:

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

【问题讨论】:

  • 链接的问题表明在 vmware 上运行时可能存在问题。你在vmware上运行吗?如果没有,您是否尝试过像答案中提供的示例那样做?
  • 我不是在vmware上运行,这是一台原生mac电脑。 @ScaryWombat

标签: java awt mouseevent


【解决方案1】:

根据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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 2021-11-14
    • 2021-06-14
    • 1970-01-01
    • 2014-11-07
    • 2021-06-12
    相关资源
    最近更新 更多