COLOR CHOOSERS

JColorChooser is a Swing class that you use to select a color. It typically pops up a window with a color chooser dialog in it. You choose a color (like blue or red), and the window goes away. The result of this process is an instance of the java.awt.Color class. A good context for JColorChooser is a word processor, where you're specifying the color to use for highlighted text.

You have three ways of selecting or entering a color with JColorChooser. You can choose a color swatch, a small square of a particular color. There's also RGB (red/green/blue) and HSB (hue/saturation/brightness) available; these represent a color using numerical values. For example, if you enter the values (255, 0, 255), you get the color magenta. You can also specify an initial color to a JColorChooser object.

JColorChooser is typically used as a pop-up modal dialog. However you can also use it as an always visible component; in this case, you are notified of color changes via event listeners.

The program sets up two regions. The upper region contains a color chooser that is set to an initial color of blue. In the lower region, a Canvas object is used to draw graphical objects. Choose a color in the upper area, and the program displays a filled oval of that color in the lower area.

Actual color changes in the JColorChooser are abstracted through a ColorSelectionModel. This is an interface that supports methods for getting and setting colors, and tracking color change. Notice that the program adds a change listener to the model. The change listener tracks changes to the current color. When a color changes, the change listener calls stateChanged to retrieve the color and draw a graphical object in the new color.