MouseListener没有响应

时间:2012-03-14 00:41:54

标签: java mouseevent awt mouselistener

我无法让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
  }
}

1 个答案:

答案 0 :(得分:1)

根据您在OP中的评论中提供的链接,您必须致电

addMouseListeners();

而不是

addMouseListener(this);

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

另一种选择是使用

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