Previous Section  < Day Day Up >  Next Section

Other Ways to Choose Colors

To use a color not included in the 13 constant variables, you must specify the color's sRGB or HSB values. sRGB, which stands for Standard Red Green Blue, defines a color by the amount of red, green, and blue that is present in the color. Each value ranges from 0, which means there is none of that color, to 255, which means the maximum amount of that color is present. Most graphics editing and drawing programs will identify a color's sRGB values.

If you know a color's sRGB values, you can use it to create a Color object. For example, an sRGB value for dark red is 235 red, 50 green, and 50 blue, and an sRGB value for light orange is 230 red, 220 green, and 0 blue. The following is an example of a panel that displays light orange text on a dark red background:

import java.awt.*;

import javax.swing.*;

public class GoBucs extends JPanel {

    Color lightOrange = new Color(230, 220, 0);

    Color darkRed = new Color(235, 50, 50);

    public void paintComponent(Graphics comp) {

        Graphics2D comp2D = (Graphics2D)comp;


        comp2D.fillRect(0, 0, 200, 100);


        comp2D.drawString("Go, Buccaneers!", 5, 50);



This example calls the fillRect() method of Graphics2D to draw a filled-in rectangle using the current color. You will learn more about this method on Hour 23.

By the Way

Light orange on a dark red background isn't any more attractive on a Java program than it was on the National Football League's Tampa Bay Buccaneers, the reason the team now wears brass-and-pewter uniforms.

Using sRGB values enables you to select from more than 16.5 million possible combinations, though most computer monitors only can offer a close approximation for most of them. For guidance on whether burnt-semidark-midnightblue goes well with medium-faded-baby-green, purchase a copy of the upcoming Sams Teach Yourself Color Sense While Waiting in Line at This Bookstore.

Another way to select a color in a Java program is the HSB system, which stands for Hue Saturation Brightness. Each of these values is represented by a floating-point number that ranges from 0.0 to 1.0. The HSB system isn't as commonly supported in graphics software, so you won't be using it as often in your programs as you use sRGB values. However, one thing HSB values are convenient for is changing a color's brightness without changing anything else about the color. You'll see an example of this use and an example of using HSB values to choose a color in this hour's workshop.

    Previous Section  < Day Day Up >  Next Section