Reputation: 19
I can't get this MouseListener
to work. Why? Nothing happens when I click th mouse
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
}
}
Upvotes: 1
Views: 1036
Reputation:
According to the link you provided in the comments in the OP, you have to call
addMouseListeners();
instead of
addMouseListener(this);
The description says: "Use the GraphicsProgram itself as a listener for mouse events that occur within the embedded GCanvas. To do so, all the student has to do is define any listener methods to which the program needs to respond and then call addMouseListeners(), which registers the program as both a MouseListener and MouseMotionListener."
The other option is to use
GCanvas canvas = getGCanvas();
canvas.addMouseListener(this);
Upvotes: 1