Using the Color Class
The simplest way to display a color in a Java program is to use one of the constant variables from the Color class. You can refer to the following constants: black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white, and yellow.
In a panel or applet window, you can set the background color of the component using these constants. The following is an example:
setBackground(Color.orange);
When you want to display text of a certain color or draw other graphics in different colors, you have to use a method that sets up the current color. You can do this from within the paintComponent() method of a container by using a setColor() method, as in the following:
public void paintComponent(Graphics comp) {
Graphics2D comp2D = (Graphics2D)comp;
comp2D.setColor(Color.orange);
comp2D.drawString("Go, Buccaneers!", 5, 50);
}
Unlike the setBackground() method, which can be called directly on a container such as a panel or applet, the setColor() method must be used on an object that can handle a color change. The preceding example shows the setColor() method of the comp2D object being used to change the current color of the container window.
|