home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book Home Java Enterprise in a Nutshell Search this book

3.17. JColorChooser

Just as JFileChooser allows the user to choose a file, javax.swing.JColorChooser allows the user to choose a color. Figure 3-6 shows a JColorChooser dialog. You can embed a JColorChooser component directly in your application or in a custom dialog box, but the most common way to use it is to simply call the static showDialog() method:

Color c = JColorChooser.showDialog(contentpane,    // Dialog appears over this
                                   "Pick a Color", // Dialog title 
                                   Color.white);   // Default color selection
figure

Figure 3-6. A JColorChooser dialog

As you can see from Figure 3-6, JColorChooser displays a color selection pane and a color preview pane. The selection pane is actually a JTabbedPane that allows colors to be selected in three different ways. The Swatches pane lets the user select a color from a palette of color swatches. With the RGB pane, the user picks a color by specifying the red, green, and blue components of the color, while with the HSV pane, the user specifies the hue, saturation, and value components of the color.

Instead of displaying a generic JColorChooser with the static showDialog() method, you can create your own instance of the JColorChooser class. You can then set properties on the color chooser object and display it in any way you want. The static JColorChooser.createDialog() method is useful here. It creates a dialog box to hold your JColorChooser pane and allows you to specify two ActionListener objects that are invoked in response to the OK and Cancel buttons in the dialog box.

You can customize a JColorChooser by adding a new color selection panel or a new color preview panel. To add a new color selection panel (for example, a panel that allows the user to select a grayscale color or a CMYK color), implement a subclass of AbstractColorChooserPanel (from the javax.swing.colorchooser package) and pass it to the addChooserPanel() method of your JColorChooser. Your custom panel contains a ColorSelectionModel that serves as the interface between your pane and the JColorChooser. All your pane needs to do is update the selected color of its ColorSelectionModel (ColorSelectionModel is also part of the javax.swing.colorchooser package).

You can use any JComponent as a custom preview panel for your JColorChooser. Simply pass the component to setPreviewPanel(). The preview component has to track the currently selected color by listening for ChangeEvent events generated by the ColorSelectionModel of the JColorChooser.



Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.