608 Graphics and Java2D Chapter 11 37 38 (Cheap web hosting)
608 Graphics and Java2D Chapter 11 37 38 // set new drawing color using static Color objects 39 g.setColor( Color.blue ); 40 g.fillRect( 25, 75, 100, 20 ); 41 g.drawString( “Current RGB: ” + g.getColor(), 130, 90 ); 42 43 // display individual RGB values 44 Color color = Color.magenta; 45 g.setColor( color ); 46 g.fillRect( 25, 100, 100, 20 ); 47 g.drawString( “RGB values: ” + color.getRed() + “, ” + 48 color.getGreen() + “, ” + color.getBlue(), 130, 115 ); 49 } 50 51 // execute application 52 public static void main( String args[] ) 53 { 54 ShowColors application = new ShowColors(); 55 56 application.setDefaultCloseOperation( 57 JFrame.EXIT_ON_CLOSE ); 58 } 59 60 } // end class ShowColors Fig. 11.5Demonstrating setting and getting a Color(part 2 of 2). Fig. 11.5 When the application begins execution, class ShowColors s paint method (lines 23 49) is called to paint the window. Line 29 uses Graphicsmethod setColor to set the current drawing color. Method setColor receives a Color object. The expression newColor(255,0,0) creates a new Color object that represents red (red value 255, and 0for the green and blue values). Line 30 uses Graphicsmethod fillRectto draw a filled rectangle in the current color. Method fillRectreceives the same parameters as method drawRect (discussed in Chapter 3). Line 31uses Graphics method drawString to draw a String in the current color. The expression g.getColor() retrieves the current color from the Graphicsobject. The returned Coloris concatenated with string “Current RGB:”, resulting in an implicit call to class Color s toString method. Notice that the String representation of the Color object contains the class name and package (java.awt.Color), and the red, green and blue values. Lines 34 36 and lines 39 41 perform the same tasks again. Line 34 uses the Color constructor with three floatarguments to create the color green (0.0ffor red, 1.0ffor green and 0.0f for blue). Note the syntax of the constants. The letter f appended to a floating-point constant indicates that the constant should be treated as type float. Normally, floating-point constants are treated as type double. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01