Using the JFC/Swing Packages |
Use Swing'sJColorChooser
class to provide users with a palette of colors to choose from. A color chooser is a component that you can place anywhere within your program's GUI. TheJColorChooser
API also makes it easy to bring up a dialog (modal or not) that contains a color chooser.Here's a picture of an application that uses a color chooser to set the background color in a banner:
The main source code for the program is in
ColorChooserDemo.java
. You will also needBanner.java
.The color chooser consists of everything within the border labelled Choose Background Color. This is the default view of a color chooser in the Metal L&F. [PENDING: check previous statement] It contains two parts, a tabbed pane and a preview panel. The three tabs in the tabbed pane each select a different chooser panel. The preview panel displays the currently selected color.
Here's the code from the example that creates a
JColorChooser
instance and adds it to the window:The constructor used to create the color chooser takes aBanner banner = new Banner(); ... final JColorChooser colorChooser = new JColorChooser(banner.getColor()); ... getContentPane().add(colorChooser, BorderLayout.CENTER);Color
argument, which specifies the initially selected color in the chooser.A color chooser uses an instance of
ColorSelectionModel
to contain and manage the current selection. The color selection model fires a change event whenever the user changes the color in the color chooser. The example program registers a change listener with the color selection model so that it can update the banner at the top of the window.Here's the code that registers and implements the change listener:
This change listener gets the currently selected color from the color chooser and uses it to set the banner's background color. See How to Write a Change Listener for general information about change listeners and change events.colorChooser.getSelectionModel().addChangeListener( new ChangeListener() { public void stateChanged(ChangeEvent e) { Color newColor = colorChooser.getColor(); banner.setColor(newColor); } } );A basic color chooser, like the one used in the example program, is sufficient for many programs. However, the color chooser API allows you to customize a color chooser by providing it with a preview panel of your own design, by adding your own chooser panels to it, or by removing existing chooser panels from the color chooser. Additionally, the color chooser class provides two methods that make it easy to use a color chooser within a dialog.
This section discusses these topics:
- ColorChooserDemo: Take 2
- Showing a Color Chooser in a Dialog
- Replacing or Removing the Preview Panel
- Creating a Custom Chooser Panel
- The Color Chooser API
- Examples that Use Color Choosers
ColorChooserDemo: Take 2
Now turn your attention toColorChooserDemo2
, a modified version of the previous demo program that uses more of theJColorChooser
API.Here's a picture of
In addition to the main source file,ColorChooserDemo2
:ColorChooserDemo2.java
, you also needCrayonPanel.java
,Banner.java
, and the four crayon images (red.gif
,yellow.gif
,green.gif
, andblue.gif
) to run this program.This program adds a GUI for changing the banner's text and for setting the banner's text color. You can invoke the color chooser for the text by clicking the Choose Text Color... button, which brings up a color chooser dialog. See Showing a Color Chooser in a Dialog for code and details.
Additionally, this program customizes the banner's background color chooser in these ways:
Replacing or Removing the Preview Panel covers the first customization. Creating a Custom Chooser Panel discusses the last two.
- Removes the preview panel
- Removes all of the default chooser panels
- Adds a custom chooser panel
Showing a Color Chooser in a Dialog
TheJColorChooser
class provides two class methods to make it easy to use a color chooser in a modal dialog. The new demo program uses one of these methods,showDialog
, to display the text color chooser when the user clicks the Choose Text Color... button. Here's the single line of code from the example that brings up the text color chooser in a modal dialog:The dialog disappears under three conditions: the user chose a color and clicked the OK button, the user cancelled the operation with the Cancel button, or the user dismissed the dialog. If the user chose a color, theColor newColor = JColorChooser.showDialog(ColorChooserDemo.this, "Choose Text Color", banner.getTextColor());showDialog
method returns the new color. If the user cancelled the operation or dismissed the window, the method returnsnull
. Here's the code from the example that updates the banner's text color according to the value returned byshowDialog
:if (newColor != null) { banner.setTextColor(newColor); }JColorChooser
provides another method to help you use a color chooser in a dialog. ThecreateDialog
method creates and returns a dialog, letting you specify action listeners for the OK and Cancel buttons in the dialog window. UseJDialog
'sshow
method to display the dialog created by this method.See [PENDING: Kathy's going to write one in table somewhere. Right?] for an example that uses this method.
Replacing or Removing the Preview Panel
By default, the color chooser displays a preview panel.
Note: Swing releases 1.1 Beta 2 and earlier contain a bug such that thesetPreviewPanel
method throws aNullPointerException
. Thus we've been unable to test and verify this section.
The example program removes the preview panel with this line of code:
This effectively removes the preview panel because a plaincolorChooser.setPreviewPanel(new JPanel());JPanel
has no size and no default view.To provide a custom preview panel, you also use
setPreviewPanel
. The component you pass into the method should inherit fromJComponent
, specify a reasonable size, and provide a customized view of the current color (obtained with theComponent
getColor
method [PENDING: check!!]). In fact, after adding agetPreferredSize
method toBanner
, you could use aBanner
instance as a preview panel. [PENDING: CHECK!!! Maybe we ought to write an example, just to check these facts.]Creating a Custom Chooser Panel
The default color chooser provides three chooser panels:You can extend the default color chooser by adding chooser panels of your own design or you can limit it by removing chooser panels.
- Swatches -- for choosing a color from a collection of swatches.
- HSB -- for choosing a color using the Hue-Saturation-Brightness color model.
- RGB -- for choosing a color using the Red-Green-Blue color model.
ColorChooserDemo2
does both: it removes all of the default panels in the color chooser then adds one of its own.Here's the code that removes the default chooser panels:
The code is straighforward: it uses//Remove the default chooser panels AbstractColorChooserPanel panels[] = colorChooser.getChooserPanels(); for (int i = 0; i < panels.length; i ++) { colorChooser.removeChooserPanel(panels[i]); }getChooserPanels
to get an array containing all of the chooser panels in the color chooser. Next, the code loops through the array and removes each panel by callingremoveChooserPanel
.The program uses the following code to add an instance of
CrayonPanel
as a chooser panel of the color chooser:colorChooser.addChooserPanel(new CrayonPanel());
Note: Swing releases 1.1 Beta 2 and earlier contain a bug that causes theaddChooserPanel
method to generate aNullPointerException
. SeeColorChooserDemo2.java
for the suggested workaround.
CrayonPanel
is a subclass ofAbstractColorChooserPanel
and overrides the five abstract methods defined in its superclass:
void updateChooser()
- This method is called whenever the chooser panel is displayed. The example's implementation of this method selects the toggle button that represents the currently selected color.
public void updateChooser() { Color color = getColorFromModel(); if (color.equals(Color.red)) { redCrayon.setSelected(true); } else if (color.equals(Color.yellow)) { yellowCrayon.setSelected(true); } else if (color.equals(Color.green)) { greenCrayon.setSelected(true); } else if (color.equals(Color.blue)) { blueCrayon.setSelected(true); } }void buildChooser()
- Creates the GUI that comprises the chooser panel. The example creates four toggle buttons -- one for each crayon -- and adds them to the chooser panel.
String getDisplayName()
- Returns the display name of the chooser panel. The name is used on the tab for the chooser panel. Here's the example's
getDisplayName
method:public String getDisplayName() { return "Crayons"; }Icon getSmallDisplayIcon()
- Returns a small icon to represent this chooser panel. The icon is used for the tab for the chooser panel. [PENDING: CHECK!] The example's implementation of this method returns
null
.
Icon getLargeDisplayIcon()
- Returns a small icon to represent this chooser panel. The icon is used for [PENDING: what?]. The example's implementation of this method returns
null
. In addition to these overridden methods,CrayonPanel
has one constructor that just callssuper()
.The Color Chooser API
The following tables list the commonly usedJColorChooser
constructors and methods.The API for using color choosers falls into these categories:
- Creating and Displaying a Color Chooser
- Customizing the Color Chooser's UI
- Setting or Getting the Current Selection
Creating and Displaying a Color Chooser Method Purpose JColorChooser()
JColorChooser(Color)
JColorChooser(ColorSelectionModel)Create a color chooser. The default constructor creates a color chooser with an initial color of white. Use the second constructor to specify a different initial color. The ColorSelectionModel
argument, when present, provides the color chooser with a color selection model.Color showDialog(Component, String, Color)
Create and show a color chooser in a modal dialog. The Component
argument is the dialog's parent, theString
argument specifies the dialog's title, and theColor
argument specifies the chooser's initial color. JDialog createDialog(Component, String, boolean, JColorChooser, ActionListener, ActionListener)Create a dialog for the specified color chooser. As with showDialog
, theComponent
argument is the dialog's parent and theString
argument specifies the dialog's title. Theboolean
argument specifies whether the dialog is modal. The firstActionListener
is for the OK button, the second is for the Cancel button.
Customizing the Color Chooser's UI Method Purpose void setPreviewPanel(JComponent)
JComponent getPreviewPanel()Set or get the component used to preview the color selection. To remove the preview panel, use new JPanel()
. To specify the default preview panel, usenull
.void setChooserPanels(AbstractColorChooserPanel[])
AbstractColorChooserPanel[] getChooserPanels()Set or get the chooser panels in the color chooser. void addChooserPanel(AbstractColorChooserPanel)
AbstractColorChooserPanel removeChooserPanel(AbstractColorChooserPanel)Add a chooser panel to the color chooser or remove a chooser panel from it.
Setting or Getting the Current Selection Method Purpose void setColor(Color)
void setColor(int, int, int)
void setColor(int)
Color getColor()Set or get the currently selected color. The three integer arguments to setColor
specify the RGB values of the color. The single integer argument tosetColor
specifies the color in RGB as well. The high-order 8 bits specify red, next 8 bits specify green, and the low-order 8 bits specify blue.void setSelectionModel(ColorSelectionModel)
ColorSelectionModel getSelectionModel()Set or get the selection model for the color chooser. This object contains the current selection and fires change events to registered listeners whenever the selection changes. Examples that Use Color Choosers
This table shows the examples that useJColorChooser
and where those examples are described.
Example Where Described Notes ColorChooserDemo.java
This page Uses a basic color chooser. ColorChooserDemo2.java
This page Use one customized color chooser and one created with showDialog
.
Using the JFC/Swing Packages |