WhileRailroad


Your browser is ignoring the <APPLET> tag!

This program uses a while loop to draw railroad ties.

import objectdraw.*;
import java.awt.*;

/** Draw railroad tracks on the canvas.
 *  The purpose of this example is to demonstrate a while loop.
 */
public class WhileRailroad extends WindowController {
    // The distance between the rails
    private static final int GAUGE = 100;
    
    // The width of the rails
    private static final int RAIL_WIDTH = 10;
    
    // The width of the rail ties
    private static final int TIE_WIDTH = 20;
    
    // The amount the rail tie should extend beyond the rails
    private static final int TIE_EXTEND = TIE_WIDTH;
    
    // The length of a rail tie
    private static final int TIE_LENGTH = GAUGE + 2 * RAIL_WIDTH +
        2 * TIE_EXTEND;
        
    // The amount of space between rail ties.
    private static final int TIE_SPACING = 25;

    // Colors of the various components drawn on the canvas.
    private final Color GROUND_COLOR = new Color(50, 150, 50);
    private final Color RAIL_COLOR = new Color(200, 200, 200);
    private final Color TIE_COLOR = new Color(150, 40, 40);

    /**
     * Draw a railroad track with grass for a background.
     */
    public void begin()
    {
        resize (600, 600);
        // Figure out the sizes of things that depend on the 
        // size of the canvas.
        int screenHeight = canvas.getHeight();
        int screenWidth = canvas.getWidth();
        
        // Center the train tracks vertically
        int trackTop = (screenHeight - GAUGE) / 2;
        int tieTop = trackTop - TIE_EXTEND;
        
        // Draw the grass background
        new FilledRect(0, 0, screenWidth, screenHeight,
                       canvas).setColor(GROUND_COLOR);
                       
        // Set the left position for the leftmost track
        double tiePosition = 5;
        
        // A while loop has three critical parts:
        //  - On each iteration, draw 1 tie
        //  - Stop when we have reached the right edge of the canvas
        //  - On each iteration, increase tiePosition so that the next
        //    tie is drawn further to the right.  This also ensures that
        //    the loop will stop since we will eventually reach the
        //    right edge of the canvas.
        while (tiePosition < screenWidth) {

            new FilledRect(tiePosition, tieTop, TIE_WIDTH, TIE_LENGTH,
                           canvas).setColor(TIE_COLOR);

            tiePosition = tiePosition + TIE_WIDTH + TIE_SPACING;
        }
        
        // Draw the 2 rails on top of the ties.
        new FilledRect(0, trackTop, screenWidth, RAIL_WIDTH, canvas).setColor(RAIL_COLOR);
        new FilledRect(0, trackTop + GAUGE, screenWidth, RAIL_WIDTH, canvas).setColor(RAIL_COLOR);
    }
}