1  /*
  2   *  File:  ColorBoxes5.java
  3   *
  4   *  Display built-in colors with labels, a 2D array, a nested loop,
  5   *  and some constants
  6   *
  7   *  Copyright:  Northeast Parallel Architectures Center
  8   *  
  9   */
 10  
 11  import java.applet.Applet;
 12  import java.awt.Graphics;
 13  import java.awt.Color;
 14  import java.awt.FontMetrics;
 15  
 16  public class ColorBoxes5 extends Applet {
 17  
 18     // size of each color swatch:
 19     private final int swatchSize = 70;
 20     // whitespace around each color swatch:
 21     private final int border = 15;
 22     // total size, including whitespace:
 23     private final int unitSize = swatchSize + 2*border;
 24     // number of color swatches per row:
 25     private final int cols = 4;
 26  
 27     // Initialize two-dimensional color array:
 28     private Color color[][] = {
 29        { Color.black, Color.blue, Color.cyan, Color.darkGray },
 30        { Color.gray, Color.green, Color.lightGray, Color.magenta },
 31        { Color.orange, Color.pink, Color.red, Color.white },
 32        { Color.yellow }
 33     };
 34     
 35     // Initialize two-dimensional array of color strings:
 36     private String colorString[][] = {
 37        { "black", "blue", "cyan", "darkGray" },
 38        { "gray", "green", "lightGray", "magenta" },
 39        { "orange", "pink", "red", "white" },
 40        { "yellow" }
 41     };
 42     
 43     public void paint( Graphics g ) {
 44        
 45        int x, y;  // local variables:
 46        
 47        // vertical adjustment for color labels:
 48        int descender = g.getFontMetrics().getDescent();
 49        
 50        // Draw rows of color boxes:
 51        for ( int i = 0; i < color.length; i++ ) {
 52           y = border + unitSize*i;
 53           for ( int j = 0; j < color[i].length; j++ ) {
 54              x = border + unitSize*j;
 55              g.setColor( color[i][j] );
 56              g.fillRect( x, y, swatchSize, swatchSize );
 57              g.setColor( Color.black );
 58              g.drawString( colorString[i][j], x, y - descender );
 59           }
 60        }
 61        
 62     }
 63  
 64  }
 65