【问题标题】:MouseListener Not Responding鼠标监听器没有响应
【发布时间】:2012-03-30 11:09:11
【问题描述】:

我无法让这个MouseListener 工作。为什么?当我点击鼠标时没有任何反应

import acm.program.*;
import acm.graphics.*;
import java.awt.event.*;

/** Draws an oval whenever the user clicks the mouse */
public class DrawOvals extends GraphicsProgram implements MouseListener {
  public void run() {
    addMouseListener(this);
  }

  public void mouseClicked(MouseEvent e) {
    GOval oval = new GOval(100,100,OVAL_SIZE, OVAL_SIZE);
    oval.setFilled(true);
    add(oval, e.getX(), e.getY());
    System.out.println("Got here!");
  }

  /* Private constants */
  private static final double OVAL_SIZE = 20;

  /* implements the required methods for mouse listener*/
  public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub
  }

  public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub
  }
}

【问题讨论】:

  • 你说不行,是什么症状?
  • 是否调用了 mouseClicked 方法?尝试在方法中放入 System.out.println("Got here!") 以查看。
  • @Roy。当我在图形窗口上单击鼠标时,什么也没有发生。我按照你的建议做了,控制台上也没有打印任何内容,所以我猜 mouseClicked 方法没有被调用。
  • 你在哪里打电话给run()?如果没有,这些都不起作用...
  • @Jon 我是 Java 的学生。我们被告知使用 run() 作为启动方法,Eclipse 将执行它作为类的起点。它适用于我编写的其他几个程序。

标签: java mouseevent awt mouselistener


【解决方案1】:

根据您在OP中的cmets中提供的链接,您必须调用

addMouseListeners();

而不是

addMouseListener(this);

描述说: “使用 GraphicsProgram 本身作为嵌入式 GCanvas 中发生的鼠标事件的侦听器。为此,学生所要做的就是定义程序需要响应的任何侦听器方法,然后调用 addMouseListeners(),它注册作为 MouseListener 和 MouseMotionListener 的程序。”

另一种选择是使用

GCanvas canvas = getGCanvas();
canvas.addMouseListener(this);

【讨论】:

    猜你喜欢
    • 2013-07-20
    • 2014-12-13
    • 2014-02-21
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    相关资源
    最近更新 更多