Java Reference
In-Depth Information
Listening for Color Selection Changes
The JColorChooser uses a ColorSelectionModel as its data model. As the following interface
definition shows, the data model includes a single property, selectedColor , for managing the
state of the color chooser.
public interface ColorSelectionModel {
// Listeners
public void addChangeListener(ChangeListener listener);
public void removeChangeListener(ChangeListener listener);
// Properties
public Color getSelectedColor();
public void setSelectedColor(Color newValue);
}
When a user changes the color within the JColorChooser , the selectedColor property changes,
and the JColorChooser generates a ChangeEvent to notify any registered ChangeListener objects.
Therefore, to complete the earlier ColorSample example in the previous section, and have
the foreground color of the label change when the user changes the color selection within the
JColorChooser , you need to register a ChangeListener with the color chooser. This involves
creating a ChangeListener and adding it to the ColorSelectionModel . Placing the source code
shown in Listing 9-8 where the //More source to come comment appears in the Listing 9-7 is
necessary for this example to work properly.
Listing 9-8. Activating the JColorChooser Example
ColorSelectionModel model = colorChooser.getSelectionModel();
ChangeListener changeListener = new ChangeListener() {
public void stateChanged(ChangeEvent changeEvent) {
Color newForegroundColor = colorChooser.getColor();
label.setForeground(newForegroundColor);
}
};
model.addChangeListener(changeListener);
Once this source is added, the example is complete. Running the program brings up
Figure 9-18, and selecting a new color alters the foreground of the label.
Creating and Showing a JColorChooser Pop-Up Window
Although the previous example is sufficient if you want to include a JColorChooser within your
own window, more often than not, you want the JColorChooser to appear in a separate pop-up
window. This window might appear as the result of selecting a button on the screen, or possibly
even selecting a menu item. To support this behavior, the JColorChooser includes the following
factory method:
public static Color showDialog(Component parentComponent,
String title, Color initialColor)
Search WWH ::




Custom Search