I'm working on these online Stanford lessons on Java, and we just made the leap to events, and I'm having difficulty wrapping my head around it. I'm playing around with a program that is in the "Art and Science of Java" book. This program will move a rectangle and oval around on the canvas if you click on them.
I modified the run method to try and get the listener to only work on the rectangle, but I was surprised to see even with my changes, both objects are being listened to...why?
Original run method:
public void run() {
GRect rect = new GRect(100, 100, 150, 100);
rect.setFilled(true);
rect.setColor(Color.RED);
add(rect);
GOval oval = new GOval(300, 115, 100, 70);
oval.setFilled(true);
oval.setColor(Color.GREEN);
add(oval);
addMouseListeners();
}
My changed program (with the MouseListener in the private createRectangle method):
import java.awt.*;
import java.awt.event.*;
import acm.graphics.*;
import acm.program.*;
/** This class displays a mouse-draggable rectangle and oval */
public class DragObjects extends GraphicsProgram {
public void run() {
createRectangle();
createOval();
}
private void createOval(){
GOval oval = new GOval(300, 115, 100, 70);
oval.setFilled(true);
oval.setColor(Color.GREEN);
add(oval);
}
private void createRectangle(){
GRect rect = new GRect(100, 100, 150, 100);
rect.setFilled(true);
rect.setColor(Color.RED);
add(rect);
addMouseListeners();
}
/** Called on mouse press to record the coordinates of the click */
public void mousePressed(MouseEvent e) {
lastX = e.getX();
lastY = e.getY();
gobj = getElementAt(lastX, lastY);
}
/** Called on mouse drag to reposition the object */
public void mouseDragged(MouseEvent e) {
if (gobj != null) {
gobj.move(e.getX() - lastX, e.getY() - lastY);
lastX = e.getX();
lastY = e.getY();
}
}
/** Called on mouse click to move this object to the front */
public void mouseClicked(MouseEvent e) {
if (gobj != null) gobj.sendToFront();
}
/* Instance variables */
private GObject gobj; /* The object being dragged */
private double lastX; /* The last mouse X position */
private double lastY; /* The last mouse Y position */
}