Computer Science 252
Problem Solving with Java
Spring 2015, The College of Saint Rose
Railroad Demo
A working demo of Railroad will appear below. Click inside the applet to interact with it.
Railroad BlueJ Project
Click here to download a BlueJ project for Railroad.
Railroad Source Code
The Java source code for Railroad is below. Click on a file name to download it.
import objectdraw.*; import java.awt.*; /* * Example Railroad -- draw a railroad track with a loop * * Jim Teresco, Siena College, CSIS 120, Spring 2011, Spring 2012 * Updated for The College of Saint Rose, Fall 2013 * * $Id: Railroad.java 2218 2013-10-18 14:06:39Z terescoj $ */ public class Railroad extends WindowController { // dimensions of the part of the canvas we'll use private static final int SCREEN_HEIGHT = 400; private static final int SCREEN_WIDTH = 400; // distance between rails private static final double GAUGE = 100; // where to start top rail private static final double TRACK_TOP = (SCREEN_HEIGHT - GAUGE) / 2; // width of rail private static final double RAIL_WIDTH = 10; // width of tie private static final double TIE_WIDTH = 20; // how far tie extends beyond rails private static final double TIE_EXTEND = 20; // length of tie private static final double TIE_LENGTH = GAUGE + 2 * RAIL_WIDTH + 2 * TIE_EXTEND; // distance between successive ties private static final double TIE_SPACING = 25; // coordinate of top of ties private static final double TIE_TOP = TRACK_TOP - TIE_EXTEND; // x coordinate of first tie private static final double FIRST_TIE_X = 5; // colors of ground, rails, and ties 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); // rails of track private FilledRect rail1, rail2; public void begin() { // draw rails and background new FilledRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, canvas).setColor(GROUND_COLOR); rail1 = new FilledRect(0, TRACK_TOP, SCREEN_WIDTH, RAIL_WIDTH, canvas); rail1.setColor(RAIL_COLOR); rail2 = new FilledRect(0, TRACK_TOP + GAUGE, SCREEN_WIDTH, RAIL_WIDTH, canvas); rail2.setColor(RAIL_COLOR); // the first tie will be drawn here double tiePosition = FIRST_TIE_X; // draw each successive tie as long as it will be on the canvas while ( tiePosition < SCREEN_WIDTH ) { new FilledRect(tiePosition, TIE_TOP, TIE_WIDTH, TIE_LENGTH, canvas).setColor(TIE_COLOR); // move rails on top of new tie rail1.sendToFront(); rail2.sendToFront(); // update position for next tie tiePosition = tiePosition + TIE_WIDTH + TIE_SPACING; } } }