Computer Science 120
Introduction to Programming

Spring 2012, Siena College

ColorfulSunset Demo

A working demo of ColorfulSunset will appear below. Click inside the applet to interact with it.

ColorfulSunset BlueJ Project

Click here to download a BlueJ project for ColorfulSunset.

ColorfulSunset Source Code

The Java source code for ColorfulSunset is below. Click on a file name to download it.

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

 * Example ColorfulSunset
 * Better simulation of the sun setting in which it changes color from
 * yellow to red.  This program also illustrates what happens when you
 * attempt to create a color with values out of the 0..255 range.  The
 * error occurs once the sun has dropped slightly below the horizon.
 * Jim Teresco, Siena College, CSIS 120, Spring 2011
 * Based on example from Williams College, CSCI 134
 * $Id: 1516 2011-01-31 21:08:19Z terescoj $

public class ColorfulSunset extends WindowController {
    private FilledRect sky;
    private FilledRect grass;
    private FilledOval sun;

    private static final int SCENE_WIDTH = 400;
    private static final int SKY_HEIGHT = 250;
    private static final int GROUND_HEIGHT = 150;
    private static final int SUN_X = 80;
    private static final int SUN_Y = 0;
    private static final int SUN_DIAMETER = 100;

    private static final int VELOCITY = 1;  // rate at which the sun moves.

    /* colors for the sun */
    private static final int RED_AMOUNT = 255;
    private static final int BLUE_AMOUNT = 0;

    private int greenAmount = 255;  // not constant, so I can vary it

     * Set up initial scene.
    public void begin() {
        sky = new FilledRect(0, 0, SCENE_WIDTH, SKY_HEIGHT, canvas);
        sun = new FilledOval(SUN_X, SUN_Y, SUN_DIAMETER, SUN_DIAMETER, canvas);
        grass = new FilledRect(0, SKY_HEIGHT, SCENE_WIDTH, GROUND_HEIGHT, canvas);


        sun.setColor(new Color(RED_AMOUNT, greenAmount, BLUE_AMOUNT));

     * Move the sun down the screen,
     * changing its color gradually by removing a bit of green
     * on each step.
    public void onMouseMove(Location point) {

        sun.move(0, VELOCITY);

        // remove a little green from the color we're about to create
        // the following is a shorthand for: greenAmount = greenAmount - 1;  
        The above may cause greenAmount to become < 0, which will cause
        the program to crash when we use it as a parameter to the 
        new Color construction.  To fix, we can replace the above line with
        an if statement that prevents it from becoming negative:

        if (greenAmount > 0) {

        sun.setColor(new Color(RED_AMOUNT, greenAmount, BLUE_AMOUNT));