JColorChooser

1. JColorChooser Basics

JColorChooser is a component that is new to Swing; there is no AWT equivalent. It lets the user interactively select a Color. The default behavior is to present a dialog box containing a tabbed pane letting the user choose via swatches, HSB values, or RGB values.

The simplest use is very simple indeed; call JColorChooser.showDialog, supplying three arguments. The first argument is the parent Component, the second is the title, and the third is the initially selected color. If the user selects "OK," the return value is the Color chosen. If the user cancels, the return value is null.

You can also allocate JColorChooser via a constructor. This is common if you want to display it somewhere other than in a popup dialog, or if you are likely to pop it up many times. In the latter case, pass the JColorChooser instance to JColorChooser.createDialog.

2. JColorChooser Example

The following example creates a small JFrame with a button that pops up a JColorChooser. The background color of the content pane is set to the color selected.

3. JColorChooserTest.java (Download source code)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
                
public class JColorChooserTest extends JFrame
                               implements ActionListener {
  public static void main(String[] args) {
    new JColorChooserTest();
  }

  public JColorChooserTest() {
    super("Using JColorChooser");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    Container content = getContentPane();
    content.setBackground(Color.white);
    content.setLayout(new FlowLayout());
    JButton colorButton
      = new JButton("Choose Background Color");
    colorButton.addActionListener(this);
    content.add(colorButton);
    setSize(300, 100);
    setVisible(true);
  }

  public void actionPerformed(ActionEvent e) {
    // Args are parent component, title, initial color
    Color bgColor
      = JColorChooser.showDialog(this,
                                 "Choose Background Color",
                                 getBackground());
    if (bgColor != null)
      getContentPane().setBackground(bgColor);
  }
}
Note: also requires WindowUtilities.java and ExitListener.java, shown earlier.

4. JColorChooserTest Initial Window

JColorChooserTest: Initial Window

5. JColorChooser Default (Swatches) Window

JColorChooser: Swatches Window

6. JColorChooser HSB Window

JColorChooser: HSB Window

7. JColorChooser RGB Window

JColorChooser: RGB Window


This page is part of my Quick Swing Tutorial for AWT Programmers. © 1999 Marty Hall. All source code freely available for unrestricted use. Created for for work in the Research and Technology Development Center of the Johns Hopkins University Applied Physics Lab, for courses in the Johns Hopkins Part-Time MS Program in Computer Science, and for various industry seminars and Java short courses.