Previous | Next | Trail Map | Creating a User Interface | Using the JFC/Swing Packages

How to Use Color Choosers


Note: This page is under construction. We're including this page in rough draft form to provide you with the latest information available. Please bear with us while we scribble as fast as we can.
This page will cover the JColorChooser(in the API reference documentation) class. For now, we provide an (unfinished) example and a brief description of the code.

Here's a scaled-down picture of an application that uses two color choosers:

The source for this program is in ColorChooserDemo.java and ColorSwatch.java.

The most obvious color chooser is the one at the bottom of the window. This is an instance of the JColorChooser class, which is a subclass of JComponent. Like other Swing components, you can create a color chooser and add it to a container. Here's the code from the example that does this:

final JColorChooser colorChooser = new JColorChooser(swatch.getColor());
colorChooser.getSelectionModel().addChangeListener(new ChangeListener()
{
    public void stateChanged(ChangeEvent e) {
	Color newColor = colorChooser.getColor();
	swatch.setColor(newColor);
    }
});
colorChooser.setBorder(BorderFactory.createTitledBorder(
					"Choose Background Color"));
...
getContentPane().add(colorChooser, BorderLayout.SOUTH);
If you click the Choose Text Color button, you invoke the other color chooser in the program. This color chooser appears in a modal dialog. Here's the code that brings up the color chooser dialog:
Color newColor = JColorChooser.showDialog(ColorChooserDemo.this,                                                           "Choose Text Color",
					   swatch.getTextColor());
if (newColor != null)
    swatch.setTextColor(newColor);
Stay tuned...more to come.

The Color Chooser API

[PENDING]

Examples that Use JColorChooser

This table shows the examples that use JColorChooser and where those examples are described.

Example Where Described Notes
ColorChooserDemo.java This page Uses two color choosers: one instance of JColorChooser and one created with showDialog.


Previous | Next | Trail Map | Creating a User Interface | Using the JFC/Swing Packages