Reputation: 19
What I'm trying to do is basically the thing you can do in the desktop when you click and drag te mouse making a square. The problem is I don't know how to make it draw "backwards" or how to clean the previous parameters when you start a new square. here is the entire code:
public void paint (Graphics j){
super.paint(j);
j.drawRect(x,y,z,w);
}
private void formMousePressed(java.awt.event.MouseEvent evt) {
x=evt.getX();
y=evt.getY();
repaint();
}
private void formMouseDragged(java.awt.event.MouseEvent evt) {
z=evt.getX();
w=evt.getY();
repaint();
}
Upvotes: 0
Views: 353
Reputation: 7812
The signature for drawRect is: drawRect(int x, int y, int width, int height)
. You need to calculate the top left corner of the square, and the width and height.
The top-left corner is (min(x, z), min(y, w))
.
The width is abs(x-z)
and the height is abs(y-w)
Putting this together we get
Try
j.drawRect(Math.min(x, z), Math.min(y, w), Math.abs(x - z), Math.abs(y - w));
Why does this work? Well you're given 2 points. It's a well known fact that 2 points can determine a square(opposite corners). The first problem is that you have to translate the points you're given, into an input that java likes. In this case, you first need the upper left hand corner. You don't know which point you have is that corner, or actually it could be that neither of them are.
So what do we know about the upper left corner? We know that it's x value is the smallest x value that exists in the square. We also know that at least one of the 2 points given rest on that same edge. Using this information we can determine that the x coordinate of the top left corner is the smallest x value of our 2 points. Or min(x, z)
. We use the same procedure to find the y coordinate.
Now width and height are easy. The width is the right edge - the left edge. We don't know which point is the right side, and which is the left side, but it doesn't matter. If we take the absolute value of the difference will always give you the positive difference between the points. In this case abs(x-z)
. The process is the same for the height.
As for resetting the square try adding a formMouseReleased
method and setting x, y, z, w to 0.
Upvotes: 1
Reputation: 12
I think you might create a method that resets the parameters something like: void modifyMouse() in your Mouse class //your parameters=0
I might try to give you a better help if you clarify your question, for now try that.
Upvotes: 0