A week into it, and I am just banging my head up against this problem. It should be a simple excersise:
I have a rectangle. I click and drag the rectangle on an x axis. The rectangle should only move within a set bounding area (the canvas), so if the canvas is 200 px wide, then the x coordinate should only go from 0 to getWidth()-RECTANGLE_WIDTH.
Simple enough, but I just can not get the darn thing to work.
Below is my unwieldy code.
I have attached two GLabels to view coordinates. I noticed that the mouseMoved label will only display coordinates within the canvas (what I want), but the mouseDragged label will go negative, and will also show coordinates beyond the canvas-this is also where the rectangle object movement is being controlled. Im'm not sure why those two behaviors are different.
Right now, my statement below:
if ((gobj.getX()) > 0 && (gobj.getX()) < (APPLICATION_WIDTH - PADDLE_WIDTH)){
gobj.move(e.getX() - lastX, 0);
}
what that statement does so far is get the rectangle to the edge, but then it just sticks there and won't return. I'm pulling my hair out on this thing...
import java.awt.*;
import java.awt.event.*;
import acm.graphics.*;
import acm.program.*;
/** This class displays a mouse-draggable rectangle and oval */
public class DragObject extends GraphicsProgram {
private static final int PADDLE_WIDTH = 150;
public static final int APPLICATION_WIDTH = 700;
public void run() {
GRect rect = new GRect(100, 100, 150, 100);
rect.setFilled(true);
rect.setColor(Color.RED);
add(rect);
label2 = new GLabel ("");
add(label2, 300, 400);
label = new GLabel ("");
add(label, 300, 300);
addMouseListeners();
}
/* these coordinates are never going beyond the canvas-even if the
* mouse does...this is good...i want this */
public void mouseMoved(MouseEvent e){
label2.setLabel("Coordinates:" + e.getX() + ", " + e.getY());
}
/** 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.getX()) > 0 && (gobj.getX()) < (APPLICATION_WIDTH - PADDLE_WIDTH)){
gobj.move(e.getX() - lastX, 0);
}
lastX = e.getX();
/* This label is active when i click the object, and does go into negative
* numbers and still counts even when off the canvas...*/
label.setLabel("Coordinates:" + e.getX() + ", " + e.getY());
}
/* Instance variables */
private GLabel label2;
private GLabel label;
private GObject gobj; /* The object being dragged */
private double lastX; /* The last mouse X position */
private double lastY; /* The last mouse Y position */
}