Color Control

Class Color declares methods and constants for manipulating colors in a Java program. The predeclared color constants are summarized in Fig. 12.3, and several color methods and constructors are summarized in Fig. 12.4. Note that two of the methods in Fig. 12.4 are Graphics methods that are specific to colors.

Figure 12.3. Color constants and their RGB values.

(This item is displayed on page 600 in the print version)

Color constant

Color

RGB value

public final static Color RED

red

255, 0, 0

public final static Color GREEN

green

0, 255, 0

public final static Color BLUE

blue

0, 0, 255

public final static Color ORANGE

orange

255, 200, 0

public final static Color PINK

pink

255, 175, 175

public final static Color CYAN

cyan

0, 255, 255

public final static Color MAGENTA

magenta

255, 0, 255

public final static Color YELLOW

yellow

255, 255, 0

public final static Color BLACK

black

0, 0, 0

public final static Color WHITE

white

255, 255, 255

public final static Color GRAY

gray

128, 128, 128

public final static Color LIGHT_GRAY

light gray

192, 192, 192

public final static Color DARK_GRAY

dark gray

64, 64, 64

Figure 12.4. Color methods and color-related Graphics methods.

(This item is displayed on page 600 in the print version)

Method

Description

Color constructors and methods

public Color( int r, int g, int b )

 

Creates a color based on red, green and blue components expressed as integers from 0 to 255.

public Color( float r, float g, float b )

 

Creates a color based on red, green and blue components expressed as floating-point values from 0.0 to 1.0.

public int getred()

 

Returns a value between 0 and 255 representing the red content.

public int getGreen()

 

Returns a value between 0 and 255 representing the green content.

public int getBlue()

 

Returns a value between 0 and 255 representing the blue content.

Graphics methods for manipulating Colors

 

public Color getColor()

 

Returns Color object representing current color for the graphics context.

public void setColor( Color c )

 

Sets the current color for drawing with the graphics context.

Every color is created from a red, a green and a blue component. Together these components are called RGB values. All three RGB components can be integers in the range from 0 to 255, or they can be floating-point values in the range 0.0 to 1.0. The first RGB component specifies the amount of red, the second the amount of green and the third the amount of blue. The larger the RGB value, the greater the amount of that particular color. Java enables the programmer to choose from 256 x 256 x 256 (or approximately 16.7 million) colors. However, not all computers are capable of displaying all these colors. The computer will display the closest color it can.

Two of class Color's constructors are shown in Fig. 12.4one that takes three int arguments and one that takes three float arguments, with each argument specifying the amount of red, green and blue. The int values must be in the range 0255 and the float values must be in the range 0.01.0. The new Color object will have the specified amounts of red, green and blue. Color methods getRed, getGreen and getBlue return integer values from 0 to 255 representing the amount of red, green and blue, respectively. Graphics method getColor returns a Color object representing the current drawing color. Graphics method setColor sets the current drawing color.

The application of Fig. 12.5Fig. 12.6 demonstrates several methods from Fig. 12.4 by drawing filled rectangles and strings in several different colors. When the application begins execution, class ColorJPanel's paintComponent method (lines 1037 of Fig. 12.5) is called to paint the window. Line 17 uses Graphics method setColor to set the current drawing color. Method setColor receives a Color object. The expression new Color( 255, 0, 0 ) creates a new Color object that represents red (red value 255, and 0 for the green and blue values). Line 18 uses Graphics method fillRect to draw a filled rectangle in the current color. Method fillRect draws a rectangle based on its four arguments. The first two integer values represent the upper-left x-coordinate and upper-left y-coordinate, where the Graphics object begins drawing the rectangle. The third and fourth arguments are nonnegative integers that represent the width and the height of the rectangle in pixels, respectively. A rectangle drawn using method fillRect is filled by the current color of the Graphics object.

Figure 12.5. Color changed for drawing.

(This item is displayed on page 601 in the print version)

 1 // Fig. 12.5: ColorJPanel.java
 2 // Demonstrating Colors.
 3 import java.awt.Graphics;
 4 import java.awt.Color;
 5 import javax.swing.JPanel;
 6
 7 public class ColorJPanel extends JPanel
 8 {
 9 // draw rectangles and Strings in different colors
10 public void paintComponent( Graphics g )
11 {
12 super.paintComponent( g ); // call superclass's paintComponent
13
14 this.setBackground( Color.WHITE );
15
16 // set new drawing color using integers
17 g.setColor( new Color( 255, 0, 0 ) );
18 g.fillRect( 15, 25, 100, 20 ); 
19 g.drawString( "Current RGB: " + g.getColor(), 130, 40 );
20
21 // set new drawing color using floats
22 g.setColor( new Color( 0.50f, 0.75f, 0.0f ) );
23 g.fillRect( 15, 50, 100, 20 );
24 g.drawString( "Current RGB: " + g.getColor(), 130, 65 );
25
26 // set new drawing color using static Color objects
27 g.setColor( Color.BLUE );
28 g.fillRect( 15, 75, 100, 20 );
29 g.drawString( "Current RGB: " + g.getColor(), 130, 90 );
30
31 // display individual RGB values
32 Color color = Color.MAGENTA;
33 g.setColor( color );
34 g.fillRect( 15, 100, 100, 20 );
35 g.drawString( "RGB values: " + color.getRed() + ", " +
36 color.getGreen() + ", " + color.getBlue(), 130, 115 );
37 } // end method paintComponent
38 } // end class ColorJPanel

Figure 12.6. Creating JFrame to display colors on JPanel.

 1 // Fig. 12.6: ShowColors.java
 2 // Demonstrating Colors.
 3 import javax.swing.JFrame;
 4
 5 public class ShowColors
 6 {
 7 // execute application
 8 public static void main( String args[] )
 9 {
10 // create frame for ColorJPanel
11 JFrame frame = new JFrame( "Using colors" );
12 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
13
14 ColorJPanel colorJPanel = new ColorJPanel(); // create ColorJPanel
15 frame.add( colorJPanel ); // add colorJPanel to frame
16 frame.setSize( 400, 180 ); // set frame size
17 frame.setVisible( true ); // displayt frame
18 } // end main
19 } // end class ShowColors
 

Line 19 uses Graphics method drawString to draw a String in the current color. The expression g.getColor() retrieves the current color from the Graphics object. The returned Color object is concatenated with string "Current RGB:", resulting in an implicit call to class Color's toString method. Note that the String representation of the Color object contains the class name and package (java.awt.Color), and the red, green and blue values.

Look-and-Feel Observation 12.1

Everyone perceives colors differently. Choose your colors carefully to ensure that your application is readable. Try to avoid using many different colors in close proximity.

Lines 2224 and lines 2729 perform the same tasks again. Line 22 uses the Color constructor with three float arguments to create a dark green color (0.50f for red, 0.75f for green and 0.0f for blue). Note the syntax of the values. The letter f appended to a floating-point literal indicates that the literal should be treated as type float. Recall that by default, floating-point literals are treated as type double.

Line 27 sets the current drawing color to one of the predeclared Color constants (Color.BLUE). The Color constants are static, so they are created when class Color is loaded into memory at execution time.

The statement in lines 3536 makes calls to Color methods getred, getGreen and getBlue on the predeclared Color.MAGENTA constant. Method main of class ShowColors (lines 818 of Fig. 12.6) creates the JFrame that will contain a ColorJPanel object where the colors will be displayed.

Software Engineering Observation 12.1

To change the color, you must create a new Color object (or use one of the predeclared Color constants). Like String objects, Color objects are immutable (not modifiable).

Package javax.swing provides the JColorChooser GUI component that enables application users to select colors. The application of Fig. 12.7Fig. 12.8 demonstrate a JColorChooser dialog. When you click the Change Color button, a JColorChooser dialog appears. When you select a color and press the dialog's OK button, the background color of the application window changes.

Figure 12.7. JColorChooser dialog.

(This item is displayed on pages 603 - 604 in the print version)

 1 // Fig. 12.7: ShowColors2JFrame.java
 2 // Choosing colors with JColorChooser.
 3 import java.awt.BorderLayout;
 4 import java.awt.Color;
 5 import java.awt.event.ActionEvent;
 6 import java.awt.event.ActionListener;
 7 import javax.swing.JButton;
 8 import javax.swing.JFrame;
 9 import javax.swing.JColorChooser;
10 import javax.swing.JPanel;
11
12 public class ShowColors2JFrame extends JFrame
13 {
14 private JButton changeColorJButton;
15 private Color color = Color.LIGHT_GRAY;
16 private JPanel colorJPanel;
17
18 // set up GUI
19 public ShowColors2JFrame()
20 {
21 super( "Using JColorChooser" );
22
23 // create JPanel for display color
24 colorJPanel = new JPanel();
25 colorJPanel.setBackground( color );
26
27 // set up changeColorJButton and register its event handler
28 changeColorJButton = new JButton( "Change Color" );
29 changeColorJButton.addActionListener(
30
31 new ActionListener() // anonymous inner class
32 {
33 // display JColorChooser when user clicks button
34 public void actionPerformed( ActionEvent event )
35 {
36 color = JColorChooser.showDialog( 
37  ShowColors2JFrame.this, "Choose a color", color );
38
39 // set default color, if no color is returned
40 if ( color == null )
41 color = Color.LIGHT_GRAY;
42
43 // change content pane's background color
44 colorJPanel.setBackground( color );
45 } // end method actionPerformed
46 } // end anonymous inner class
47 ); // end call to addActionListener
48
49 add( colorJPanel, BorderLayout.CENTER ); // add colorJPanel
50 add( changeColorJButton, BorderLayout.SOUTH ); // add button
51
52 setSize( 400, 130 ); // set frame size
53 setVisible( true ); // display frame
54 } // end ShowColor2JFrame constructor
55 } // end class ShowColors2JFrame

Figure 12.8. Choosing colors with JColorChooser.

(This item is displayed on pages 604 - 605 in the print version)

 1 // Fig. 12.8: ShowColors2.java
 2 // Choosing colors with JColorChooser.
 3 import javax.swing.JFrame;
 4
 5 public class ShowColors2
 6 {
 7 // execute application
 8 public static void main( String args[] )
 9 {
10 ShowColors2JFrame application = new ShowColors2JFrame();
11 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12 } // end main
13 } // end class ShowColors2
 

Class JColorChooser provides a static convenience method showDialog that creates a JColorChooser object, attaches it to a dialog box and displays the dialog. Lines 3637 of Fig. 12.7 invoke this method to display the color chooser dialog. Method showDialog returns the selected Color object, or null if the user presses Cancel or closes the dialog without pressing OK. The method takes three argumentsa reference to its parent Component, a String to display in the title bar of the dialog and the initial selected Color for the dialog. The parent component is a reference to the window from which the dialog is displayed (in this case the JFrame, with the reference name frame). The dialog will be centered on the parent. If the parent is null, the dialog is centered on the screen. While the color chooser dialog is on the screen, the user cannot interact with the parent component. This type of dialog is called a modal dialog (discussed in Chapter 22, GUI Components: Part 2).

After the user selects a color, lines 4041 determine whether color is null, and, if so, set color to Color.LIGHT_GRAY. Line 44 invokes method setBackground to change the background color of the JPanel. Method setBackground is one of the many Component methods that can be used on most GUI components. Note that the user can continue to use the Change Color button to change the background color of the application. Figure 12.8 contains method main, which executes the program.

The second screen capture of Fig. 12.8 demonstrates the default JColorChooser dialog that allows the user to select a color from a variety of color swatches. Note that there are actually three tabs across the top of the dialogSwatches, HSB and RGB. These represent three different ways to select a color. The HSB tab allows you to select a color based on hue, saturation and brightnessvalues that are used to define the amount of light in a color. We do not discuss HSB values. For more information on hue, saturation and brightness, visit whatis.techtarget.com/definition/0,,sid9_gci212262,00.html. The RGB tab allows you to select a color by using sliders to select the red, green and blue components. The HSB and RGB tabs are shown in Fig. 12.9.

Figure 12.9. HSB and RGB tabs of the JColorChooser dialog.


Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover



Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net