Source of DrawPanel.java


  1: // Fig. 8.22: DrawPanel.java
  2: // Program that uses class MyLine
  3: // to draw random lines.
  4: import java.awt.Color;
  5: import java.awt.Graphics;
  6: import java.util.Random;
  7: import javax.swing.JPanel;
  8: 
  9: public class DrawPanel extends JPanel
 10: {
 11:    private Random randomNumbers = new Random();   
 12:    private MyLine lines[]; // array on lines
 13: 
 14:    // constructor, creates a panel with random shapes
 15:    public DrawPanel()
 16:    {
 17:       setBackground( Color.WHITE );
 18:       
 19:       lines = new MyLine[ 5 + randomNumbers.nextInt( 5 ) ];
 20: 
 21:       // create lines
 22:       for ( int count = 0; count < lines.length; count++ )
 23:       {
 24:          // generate random coordinates
 25:          int x1 = randomNumbers.nextInt( 300 );
 26:          int y1 = randomNumbers.nextInt( 300 );
 27:          int x2 = randomNumbers.nextInt( 300 );
 28:          int y2 = randomNumbers.nextInt( 300 );
 29:          
 30:          // generate a random color
 31:          Color color = new Color( randomNumbers.nextInt( 256 ), 
 32:             randomNumbers.nextInt( 256 ), randomNumbers.nextInt( 256 ) );
 33:          
 34:          // add the line to the list of lines to be displayed
 35:          lines[ count ] = new MyLine( x1, y1, x2, y2, color );
 36:       } // end for
 37:    } // end DrawPanel constructor
 38: 
 39:    // for each shape array, draw the individual shapes
 40:    public void paintComponent( Graphics g )
 41:    {
 42:       super.paintComponent( g );
 43:       
 44:       // draw the lines
 45:       for ( MyLine line : lines )
 46:          line.draw( g );
 47:    } // end method paintComponent
 48: } // end class DrawPanel
 49: 
 50: 
 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:  *************************************************************************/