Five different colored rectangles. Draw them by dragging the mouse on the canvas. Five colors, but one .nextValue() method statement, not FIVE of them!



  1. Press down your mouse button and drag and when you release you'll see that you drew a rectangle

  2. Here is the Java code...
    import objectdraw.*;
    import java.awt.*;
    
    public class DrawRectanglesInFiveRandomColors extends WindowController
    {
       Location upperLeftCorner;
       RandomIntGenerator generator;
    
       private static final int    RED = 1;    // Five colors, five constants
       private static final int PURPLE = 2;
       private static final int ORANGE = 3;
       private static final int   BLUE = 4;
       private static final int   CYAN = 5;
        
       public void begin()
       {
          generator = new RandomIntGenerator(1, 5);
       }
    
       public void onMousePress(Location point)
       {
           upperLeftCorner = point;
       }
    
       public void onMouseRelease(Location point)
       {
           FilledRect r;
           int randomColorChoice;
    
           r = new FilledRect(upperLeftCorner, point, canvas);
    
           randomColorChoice = generator.nextValue();       
           
           if (randomColorChoice == RED)  // Note how the CONSTANTS make
           {                              // the code so much easier understand!
              r.setColor( Color.red );
           }
           else if (randomColorChoice == PURPLE)
           {
              r.setColor( Color.magenta );
           }
           else if (randomColorChoice == ORANGE)
           {
              r.setColor( Color.orange );
           }
           else if (randomColorChoice == BLUE)
           {
              r.setColor( Color.blue );
           }
           else if (randomColorChoice == CYAN)
           {
              r.setColor( Color.cyan );
           }
       }
    }
    
  3. It looks like we only needed ONE variable for the int randomly chosen color value, not FIVE variables! The RGB graphics program that did 16 million+ colors seems to have thrown many students off the track! :-) Only one statement with generator.nextValue() is needed in the class, not five statements!!