|
To access the contents, click the chapter and section titles.
Platinum Edition Using HTML 4, XML, and Java 1.2
You must import the Color class to use a Color class constant, but you dont need to make a new Color object. Just type the class name followed by the dot operator followed by the color name. For example, you can write g.setColor(Color.yellow); g.fillOval(50, 50, 200, 200); to get a yellow oval.
Javas Graphics class provides two methods for manipulating colors: the getColor() and setColor() methods. Their full definitions are: public abstract Color getColor() public abstract void setColor(Color c) The getColor() method returns the Graphics objects current color encapsulated in a Color object, and the setColor() method sets the Graphics objects color by passing it a Color object. Using Javas Color ClassThe Color class is defined in the java.awt package and has three constructors. The first constructor enables you to instantiate a Color object using explicit red (r), green (g), and blue (b) integers between 0 and 255: public Color(int r, int g, int b) The second constructor is similar to the first. Instead of integer values, it uses floating-point values between 0.0 and 1.0 for red (r), green (g), and blue (b): public Color(float r, float g, float b) The third constructor enables you to make a Color using red, green, and blue integers between 0 and 255, but you combine the three numbers into a single, typically hexadecimal, value (rgb): public Color(int rgb) In the 32-bit rgb integer, bits 16 through 23 (8 bits) hold the red value, bits 8 through 15 (8 bits) hold the green value, and bits 0 through 7 (8 bits) hold the blue value. The highest 8 bits, bits 24 through 32, are not manipulated. You usually write rgb values in hexadecimal notation so that it is easy to see the color values. A number prefaced with 0x is read as hexadecimal. For instance, 0xFFA978 would give a red value of 0xFF (255 decimal), a green value of 0xA9 (52 decimal), and a blue value of 0x78 (169 decimal). After you make a Color object, set a Graphics objects drawing color by using its setColor method. The default drawing color for Graphics objects is black. The ColorPlay applet in Listing 39.9 gets the graphics contexts default color and assigns it to the defaultColor variable by passing the color value encapsulated in a Color object. A new Color object is built by using a hexadecimal value and is assigned to the newColor variable. We draw a filled circle on the left using newColor and another on the right using the defaultColor variable. Figure 39.11 shows the resulting output.
|
Products | Contact Us | About Us | Privacy | Ad Info | Home
Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc. All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement. |