Using Colors with Applets
Java allows you to create text in any color that your computer is capable of displaying. There are two main ways that you specify colors in Java. You can specify a color by its symbolic name, for example, to change the color to red, you would use the following code.
g.setColor(Color.RED);
Java defines thirteen of these predefined colors. They are listed here.
- BLACK
- BLUE
- CYAN
- DARK_GRAY
- GRAY
- GREEN
- LIGHT_GRAY
- MAGENTA
- ORANGE
- PINK
- RED
- WHITE
- YELLOW
In addition to the predefined colors you can also create your own colors by mixing the three basic video colors:
- Red
- Green
- Blue
For example to create the color white, using red green and blue values, you would use the following code.
g.setColor( new Color(255,255,255) );
This would create white, because white is produced when all colors are present. Likewise, black can be produced when all colors are absent.
g.setColor( new Color(0,0,0) );
Most drawing programs will give you the numbers used to produce a particular color. This is a quick way to determine a color that you need. Figure 1.6 shows MS Paintbrush being used to display the RGB numbers for a color.

Figure 1.6: Using MS Paintbrush to determine RGB color numbers
I will now show you a program that cycles through most of the “red” colors provided by Java. This applet is shown in Figure 1.6.
Figure 1.6: Displaying a red gradient
The source code used to display the red gradient is shown in Listing 1.4.
Listing 1.4: Applet that uses Colors (ColorApplet.java)
import java.awt.*;
import java.applet.*;
public class ColorApplet extends Applet
{
public void paint(Graphics g)
{
for( int i = 0;i<255;i++ )
{
Color c = new Color(i,0,0);
g.setColor(c);
g.drawRect(0,i,getWidth(),i);
}
}
}
As you can see the above program displays a series of rectangles. These rectangles start a the top of the applet and are displayed downward. Each rectangle, which is only one pixel high, is displayed with increasing values for the red component of the color.



