Source of DrawRainbow.java


  1: // Fig. 7.22: DrawRainbow.java
  2: // Demonstrates using colors in an array.
  3: import java.awt.Color;
  4: import java.awt.Graphics;
  5: import javax.swing.JPanel;

  7: public class DrawRainbow extends JPanel
  8: {
  9:    // Define indigo and violet
 10:    final Color VIOLET = new Color( 128, 0, 128 );
 11:    final Color INDIGO = new Color( 75, 0, 130 );
 12:    
 13:    // colors to use in the rainbow, starting from the innermost
 14:    // The two white entries result in an empty arc in the center
 15:    private Color colors[] =
 16:       { Color.WHITE, Color.WHITE, VIOLET, INDIGO, Color.BLUE,
 17:         Color.GREEN, Color.YELLOW, Color.ORANGE, Color.RED };
 18:         
 19:    // constructor
 20:    public DrawRainbow()
 21:    {
 22:       setBackground( Color.WHITE ); // set the background to white
 23:    } // end DrawRainbow constructor
 24:         
 25:    // draws a rainbow using concentric circles
 26:    public void paintComponent( Graphics g )
 27:    {
 28:       super.paintComponent( g );
 29:       
 30:       int radius = 20; // radius of an arch
 31:       
 32:       // draw the rainbow near the bottom-center
 33:       int centerX = getWidth() / 2;
 34:       int centerY = getHeight() - 10;

 36:       // draws filled arcs starting with the outermost
 37:       for ( int counter = colors.length; counter > 0; counter-- )
 38:       {
 39:          // set the color for the current arc
 40:          g.setColor( colors[ counter - 1 ] );
 41:          
 42:          // fill the arc from 0 to 180 degrees
 43:          g.fillArc( centerX - counter * radius,
 44:             centerY - counter * radius, 
 45:             counter * radius * 2, counter * radius * 2, 0, 180 );
 46:       } // end for
 47:    } // end method paintComponent
 48: } // end class DrawRainbow


 51: /**************************************************************************
 52:  * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and               *
 53:  * Pearson Education, Inc. All Rights Reserved.                           *
 54:  *                                                                        *
 55:  * DISCLAIMER: The authors and publisher of this book have used their     *
 56:  * best efforts in preparing the book. These efforts include the          *
 57:  * development, research, and testing of the theories and programs        *
 58:  * to determine their effectiveness. The authors and publisher make       *
 59:  * no warranty of any kind, expressed or implied, with regard to these    *
 60:  * programs or to the documentation contained in these books. The authors *
 61:  * and publisher shall not be liable in any event for incidental or       *
 62:  * consequential damages in connection with, or arising out of, the       *
 63:  * furnishing, performance, or use of these programs.                     *
 64:  *************************************************************************/