Java: Rectangle2D and negative dimensions
I have a script in which the user clicks once to begin a Rectangle2D
. When he moves the mouse, the rectangle is updated with the new coordinates. He clicks again to end it. It's then stored in an ArrayList
, and a开发者_JS百科ll these items are painted. This all works fine; it's not the problem.
However, if the second click is less than the first (i.e. getWidth()
is negative), the rectangle doesn't show up (as stated in the documentation). My script to fix this doesn't work. It's supposed to detect negative values, and then 1) decrement the position value and 2) make the negatives positive. Instead, it just moves the entire rectangle up or left (depending on which axis is negative) and keeps it at 1px.
What's wrong?
private void resizeRectangle(final MouseEvent e) {
double x = rectangle.getX(), y = rectangle.getY(), w = e.getX() - x, h = e.getY() - y;
if (w < 0) {
x = e.getX();
w = -w;
}
if (h < 0) {
y = e.getY();
h = -h;
}
rectangle.setRect(x, y, w, h);
}
Thanks!
UPDATE: This is closer, but still doesn't quite work:
double x = rectangle.getX();
double y = rectangle.getY();
double w = e.getX() - x;
double h = e.getY() - y;
if (w < 0) {
x = e.getX();
w = originalClickPoint.getX() - e.getX();
}
if (h < 0) {
y = e.getY();
h = originalClickPoint.getY() - e.getY();
}
rectangle.setRect(x, y, w, h);
Once you assign the new rectangle you also shift the origin (i.e.where the mouse button was pressed down initially) to the current point. You'll have to save this point in a separate field (not in the rectangle itself).
x = Math.min(e.getX(), originalClickPoint.getX());
w = Math.abs(originalClickPoint.getX() - e.getX());
y = Math.min(e.getY(), originalClickPoint.getY());
h = Math.abs(originalClickPoint.getY() - e.getY());
Another way is to not correct the negative widths/heights of the rectangle but create a new (corrected) one when you draw it.
Take a look at the Custom Painting Approaches. The source code for the DrawOnComponent
example shows how I did this.
精彩评论