This program animates a square that moves until it is in the center of the screen. It starts on the left side.

Solution

public class GoCenter extends GraphicsProgram {
    private static final int SIZE = 20;
    private static final int DELAY = 100;
    
    public void run() {
        // Draw a square on the left of the screen.
        GRect rect = new GRect(SIZESIZE);
        double x = 0;
        double y = (getHeight() - rect.getHeight()) / 2;
        rect.setFilled(true);
        add(rectxy);
        
        // Move until the center
        // rect.getX() returns the x coordinate of the rectangle
        double maxX = (getWidth() - rect.getWidth()) /2;
        while(rect.getX() < maxX) {
            // move one pixel to the right
            rect.move(10);
            // animation pause.
            pause(DELAY);
        }
    }
}
X