javajava-canvas

Java Canvas - Rectangle2D Scales when Moving


I am drawing a series of rectangles on a Canvas. The rectangles are supposed to move on an angle. For some reason, when they move, they scale up:

xPos += xSpeed;
yPos += ySpeed;
updateBounds(xPos, yPos, width, height);

My UpdateBounds method:

public void updateBounds(double x, double y, double w, double h) {
    bounds.setRect(x, y, w, h);
}

Bounds is a Rectangle2D object. And my Drawing method:

g.fillRect((int) bounds.getX(), (int) bounds.getY(),
                (int) bounds.getMaxX(), (int) bounds.getMaxY());

Why am I getting this behaviour?


Solution

  • Graphics.fillRect() accepts a width and height parameter, not the largest x and y position of the rectangle to draw.

    The third and fourth parameters to fillRect should be Rectangle2D's getWidth() and getHeight().

    As a reference, a link to what getMaxX() would give you.