Home > Articles

  • Print
  • + Share This
This chapter is from the book

JColorChooser

Color choosers, represented by the JColorChooser class, are components that allow a color to be selected. A color chooser is composed of two separate areas: a set of color chooser panels displayed in a tabbed pane12 and a preview panel that visually communicates the selected color. Both areas can be customized by replacing the default panels.

Like file choosers and option panes, color choosers are typically displayed in a dialog, but since color choosers are components, they can be contained in any AWT or Swing container.

JColorChooser features are listed in Feature Summary 16-1.

Feature Summary 16-1 JColorChooser

Color Chooser Panels

By default, color choosers come with three panels that allow a color chooser to be selected: Swatches, HSB, and RGB. Any of the default panels can be removed, and custom panels can be added.

Preview Panel

A color chooser's selected color is communicated through a preview panel. The default preview panel can be replaced with a custom version.

Prefabricated Dialogs

JColorChooser provides two static methods: createDialog() and showDialog() that create dialogs containing color choosers. The former creates and returns a dialog containing the color chooser it is passed; the latter creates both color chooser and dialog and shows the dialog. Both dialogs are modal.

The applet shown in Figure 16-11 contains a color chooser. By default, color choosers are equipped with three chooser panels contained in a tabbed pane, each of which is shown in Figure 16-11.

Figure 11Figure 16-11 A Color Chooser Displayed in an Applet


The applet shown in Figure 16-11 creates a color chooser with the JColorChooser no-argument constructor, and the chooser is added to the applet's content pane.

Color choosers have a selection model that is an implementation of the swing.colorchooser.ColorSelectionModel interface. The applet shown in Figure 16-11 adds a change listener to the color chooser's selection model to determine when a color has been selected. The listener responds to selections by updating the applet's status area.

The applet shown in Figure 16-11 is listed in Example 16-9.

Example 16-9 A Color Chooser Displayed in an Applet

import javax.swing.*;
import javax.swing.colorchooser.*;
import javax.swing.event.*;
import java.awt.*;

public class Test extends JApplet {
  JColorChooser chooser = new JColorChooser();
  ColorSelectionModel model = chooser.getSelectionModel();

  public void init() {
    getContentPane().add(chooser, BorderLayout.CENTER);

    model.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent e) {
        showStatus("Color: " + chooser.getColor());
      }
    });
  }
}

Displaying Color Choosers In Dialogs

Color choosers can be displayed in a dialog in one of two ways. The static JColorChooser.showDialog method creates a color chooser that is placed in a newly created dialog every time the method is invoked.

The JColorChooser.createDialog method is passed an existing color chooser that is also placed in a newly created dialog every time the method is invoked.

The following sections illustrate the use of the methods described above.

Showing Color Chooser Dialogs

The applet shown in Figure 16-12 contains a grid of ColorPatch objects that are contained in a Palette; both the ColorPatch and Palette classes are implemented by the applet. The upper-left picture in Figure 16-12 shows the applet as it appears initially. The upper-right picture shows the color chooser displayed as a result of clicking on the upper-left color patch. The lower-left picture shows a message dialog that the applet displays after the color chooser has been dismissed. The lower-right picture shows the applet after white has been selected from the color chooser. The selected color is set as the background color for the color patch in which the mouse pressed event occurred.

Figure 16-12Figure 16-12 Using JFileChooser.showDialog()


The applet creates an instance of Palette, which is subsequently added to the applet's content pane.

public class Test extends JApplet {
  public void init() {
    getContentPane().add(new Palette(), BorderLayout.CENTER);
  }
}

The Palette class is a simple extension of JPanel that contains a grid of ColorPatch objects representing a set of default colors.

class Palette extends JPanel {
  private Color[] defaultColors = new Color[] {
    Color.blue, Color.red, Color.yellow, Color.green,
    Color.magenta, Color.darkGray, Color.white, Color.orange,
    Color.pink, Color.cyan, Color.lightGray, Color.gray,
  };

  public Palette() {
    int columns = 3;

    setBorder(
      BorderFactory.createTitledBorder("Color Palette"));

    setLayout(new GridLayout(columns,0,1,1));

    for(int i=0; i < defaultColors.length; ++i)
      add(new ColorPatch(defaultColors[i]));
  }  
}

ColorPatch class is the most interesting class the applet implements. ColorPatch is also an extension of JPanel with a mouse listener that invokes JColorChooser.showDialog when a mouse pressed event is detected.

JColorChooser.showDialog creates a color chooser and a modal dialog, adds the chooser to the dialog, displays the dialog, and returns a reference to the color selected from the chooser. If the dialog is canceled—by activating the color chooser's Cancel button, pressing the Esc key, or clicking the dialog's close button—the showDialog method returns a null reference.

The mouse listener for the ColorPatch class displays a message dialog with a message corresponding to whether a color was selected or the dialog was dismissed. If a color is selected, the listener sets the background color for the color patch that launched the dialog to the selected color and repaints the color patch.

class ColorPatch extends JPanel {
  JApplet applet;
  Color selectedColor;

  public ColorPatch(Color color) {
    // add border and set background color ...

    addMouseListener(new MouseAdapter() {
      public void mousePressed(MouseEvent e) {
        selectedColor = JColorChooser.showDialog(
                ColorPatch.this, // parent comp
                "Pick A Color",  // dialog title
                getBackground()); // initial color

        if(selectedColor == null) {
          JOptionPane.showMessageDialog(ColorPatch.this,
            "ColorChooser Canceled");
        }
        else {
          setBackground(selectedColor);
          repaint();

          JOptionPane.showMessageDialog(ColorPatch.this, 
            "Color Selected: " + selectedColor);
        }
      }
    });
  }
}

JColorChooser.showDialog() takes three arguments: a component over which the dialog is centered, a title for the dialog, and the color chooser's initial color.

The applet shown in Figure 16-12 is listed in its entirety in Example 16-10.

Example 16-10 A Color Chooser Displayed in a Dialog

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JApplet {
  public void init() {
    getContentPane().add(new Palette(), BorderLayout.CENTER);
  }
}
class Palette extends JPanel {
  private Color[] defaultColors = new Color[] {
    Color.blue, Color.red, Color.yellow, Color.green,
    Color.magenta, Color.darkGray, Color.white, Color.orange,
    Color.pink, Color.cyan, Color.lightGray, Color.gray,
  };

  public Palette() {
    int columns = 3;

    setBorder(
      BorderFactory.createTitledBorder("Color Palette"));

    setLayout(new GridLayout(columns,0,1,1));

    for(int i=0; i < defaultColors.length; ++i)
      add(new ColorPatch(defaultColors[i]));
  }  
}
class ColorPatch extends JPanel {
  JApplet applet;
  Color selectedColor;

  public ColorPatch(Color color) {
    setBorder(BorderFactory.createEtchedBorder());
    setBackground(color);

    addMouseListener(new MouseAdapter() {
      public void mousePressed(MouseEvent e) {
        selectedColor = JColorChooser.showDialog(
                ColorPatch.this, // parent comp
                "Pick A Color",  // dialog title
                getBackground()); // initial color

        if(selectedColor == null) {
          JOptionPane.showMessageDialog(ColorPatch.this,
            "ColorChooser Canceled");
        }
        else {
          setBackground(selectedColor);
          repaint();

          JOptionPane.showMessageDialog(ColorPatch.this, 
            "Color Selected: " + selectedColor);
        }
      }
    });
  }
}

Creating Color Chooser Dialogs

As an alternative to JColorChooser.showDialog(), the JColorChooser class provides a static createDialog method that creates a dialog, given a color chooser. The JColorChooser.createDialog method is passed six arguments:

A component over which the dialog will be centered

A string representing dialog's title

A boolean value representing the modality of the dialog

A color chooser that is placed in the dialog

Two action listeners that are notified when the color chooser's buttons are activated

The ColorPatch class listed below is similar to the one listed in Example 16-10 on page 984, except that JFileChooser.createDialog() is used instead of JFileChooser.showDialog(). The ColorPatch class listed below contains a static color chooser that is shared by all instances of the ColorPatch class. Color choosers are somewhat expensive to create; as a result, creating a color chooser for each color patch in the palette would result in a perceptible performance penalty.

class ColorPatch extends JPanel {
  JApplet applet;
  static JColorChooser chooser = new JColorChooser();
  JDialog   dialog;

  public ColorPatch(Color color) {
    setBorder(BorderFactory.createEtchedBorder());
    setBackground(color);

    addMouseListener(new MouseAdapter() {
      public void mousePressed(MouseEvent e) {
        if(dialog == null)
          dialog   = JColorChooser.createDialog(
                ColorPatch.this, // parent comp
                "Pick A Color",  // dialog title
                false,        // modality
                chooser,    
                new OkListener(), 
                new CancelListener());

        chooser.setColor(getBackground());
        dialog.setVisible(true);
      }
    });
  }
  class OkListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      Color color = chooser.getColor();
      setBackground(color);
      repaint();

      JOptionPane.showMessageDialog(chooser, 
        "Color Selected: " + chooser.getColor());
    }
  }
  class CancelListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      JOptionPane.showMessageDialog(null, 
        "ColorChooser Canceled");
        
    }
  }
}

After the mouse listener associated with the ColorPatch class creates the dialog, the chooser's color is set to the background color of the patch and the dialog is made visible.

The action listeners passed to the JFileChooser.createDialog method show a message dialog in a similar fashion to the mouse listener associated with the ColorPatch class listed in Example 16-10. If the color chooser's button is activated, the selected color is obtained with the JColorChooser.getColor method, the background of the color patch is set, and the color patch is repainted.

The applet that uses the ColorPatch class listed above is identical to the applet listed in Example 16-10, with the exception of the ColorPatch class itself. The applet is not listed; however, the listing is contained on the CD in the back of the book.

TIP

Speed vs. Convenience

The easiest way to display a color chooser in a dialog is to use the JColorChooser.showDialog method; however, there is a fairly steep price to pay for the convenience. Every time showDialog() is invoked, a newly created color chooser is displayed in a newly created dialog.

Although it requires a little more effort, manually constructing a color chooser and a dialog can result in a significant performance boost. If the applications discussed in "Showing Color Chooser Dialogs" on page 981 and "Creating Color Chooser Dialogs" on page 985 are run simultaneously, a perceptible performance difference can be seen from the time a mouse click occurs in a color patch and the color chooser dialog is displayed.

Customizing Color Choosers

By default, color choosers are fitted with three color chooser panels contained in a tabbed pane and a preview panel, as illustrated in Figure 16-1 on page 920. Although the default color chooser panels and preview panel are likely to be sufficient for most color choosers, both the color choosers panels and preview panel can be replaced with custom versions, as the following sections illustrate.

Preview Panels

When a color is selected in a color chooser, the default preview panel's foreground color is set to the selected color and the default preview panel is repainted.

A color chooser's preview component can be customized by specifying the preview component JColorChooser.setPreviewPanel(JComponent). However, although the component specified by the setPreviewPanel method is substituted for the default preview panel, custom preview panels are not updated when a color is selected due to a bug in JColorChooser in Swing 1.1 FCS.

NOTE

The following application does not work properly under Swing 1.1 FCS because of the bug cited in the previous paragraph. It should work when a subsequent release of Swing fixes the bug.

The color chooser shown in Figure 16-13 contains a custom preview panel.

Figure 16-13Figure 16-13 A Custom Preview in a Color Chooser


The application that shows the color chooser shown in Figure 16-13 is listed in Example 16-11.

Example 16-11 A Custom Preview in a Color Chooser

import javax.swing.*;
import javax.swing.colorchooser.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JApplet {
  private JColorChooser chooser = new JColorChooser();
  private JButton button = new JButton("Show Color Chooser");
  private JDialog dialog;

  public void init() {
    Container contentPane = getContentPane();

    contentPane.setLayout(new FlowLayout());
    contentPane.add(button, BorderLayout.CENTER);

    chooser.setPreviewPanel(new PreviewPanel());

    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {

        if(dialog == null) 
          dialog  = JColorChooser.createDialog(
                Test.this, // parent comp
                "Pick A Color",  // dialog title
                false,        // modality
                chooser,    
                null, null);

        dialog.setVisible(true);
      }
    });
  }
  class PreviewPanel extends JPanel {
    public PreviewPanel() {
      setPreferredSize(new Dimension(0,100));
      setBorder(BorderFactory.createRaisedBevelBorder());
    }
    public void paintComponent(Graphics g) {
      Dimension size = getSize();

      g.setColor(getForeground());
      g.fillRect(0,0,size.width,size.height);
    }
  }
}

The application sets the preview panel for its color chooser by invoking JColorChooser.setPreviewPanel(), which is passed an instance of PreviewPanel.

The PreviewPanel class extends JPanel and specifies a preferred height of 100 pixels. The preferred width for color chooser preview panels is ignored, so it is set to 0. The preview panel is fitted with a raised bevel border obtained from the Swing border factory.

When a color is selected in a color chooser, the foreground color of the preview panel is set to the selected color and the preview panel is repainted. The PreviewPanel class overrides paintComponent to fill the panel with the foreground color. Unfortunately, only the default preview panel is updated when a color is selected; as a result, the application listed in Figure 16-13 does not work as advertised.

Color Chooser Panels

The set of color chooser panels contained in a color chooser can be modified with JColorChooser.setChooserPanels() or individual panels can be added or removed with the addChooserPanel and removeChooserPanel methods. This section discusses the former.

The color chooser panels displayed in a color chooser are objects that extend the swing.colorchooser.AbstractColorChooserPanel class, which is summarized in Class Summary 15-9.

Class Summary 15-9 AbstractColorChooserPanel

Extends: JPanel

Constructors

public AbstractColorChooserPanel()

The AbstractColorChooserPanel class does not implement any constructors, and therefore the no-argument constructor is compiler generated.

Methods

Color/Color Selection Model / Installing Chooser Panel / Painting

public ColorSelectionModel getColorSelectionModel()
protected Color getColorFromModel()

public void installChooserPanel(JColorChooser)
public void uninstallChooserPanel(JColorChooser)

public void paint(Graphics)

The first two methods listed above are convenience methods that return the selection model associated with the panel's color chooser, and the color maintained by the selection model, respectively.

The installChooserPanel method is invoked when a color chooser is instantiated. The method invokes buildChooser() and updateChooser() and adds a change listener to the color chooser's selection model. The listener works in concert with the paint method so that updateChooser() is invoked when the panel is painted if changes have been made to the chooser's selection model before the chooser is displayed.

The uninstallChooserPanel method removes the listener that was added to the chooser's selection model by the installChooserPanel method.

Building and Updating Chooser

protected abstract void buildChooser()
public abstract void updateChooser()

The buildChooser method is invoked when a color chooser's chooser panels are set with the JColorChooser.setChooserPanels method. The buildChooser method is expected to create the components contained in the panel and to add the components to the panel.

The updateChooser method is also invoked when color chooser panels are set with the JColorChooser.setChooserPanels method. Additionally, updateChooser() is invoked when a change is made to the chooser's color selection model.

The buildChooser and updateChooser methods are abstract and therefore must be implemented by concrete extensions of AbstractColorChooserPanel.

Display Names and Icons

public abstract String getDisplayName()
public abstract Icon getLargeDisplayIcon()
public abstract Icon getSmallDisplayIcon()

The three methods listed above return information about a color chooser panel. As of Swing 1.1 FCS / 1.2 JDK, only the getDisplayName method is used for the string displayed in the tab associated with a panel. For example, the default display names for the default chooser panels are "Swatches", "HSB", and "RBG", as can be seen from Figure 16-11 on page 980. The icons returned from getLargeDisplayIcon() and getSmallDisplayIcon() are not currently used within Swing.

The applet shown in Figure 16-14 contains a button whose activation results in a color chooser being displayed in a dialog. The default chooser panels in the color chooser are replaced by an extension of the AbstractColorChooserPanel class. It should be noted that the chooser panel contained in the color chooser shown in Figure 16-14 is short on usability and long on simplicity for the sake of illustration.

Figure 16.14Figure 16-14 Replacing Chooser Panels


The applet creates a color chooser and an array of objects that implement the AbstractColorChooserPanel class. The array contains a single instance of ListPanel, which is implemented by the applet. Notice that the ListPanel instance is not contained in a tabbed pane because only one chooser panel is contained in the array.

The applet's init method invokes JColorChooser.setChooserPanels(), passing the array of color chooser panels.

public class Test extends JApplet {
  private JColorChooser chooser = new JColorChooser();
  private AbstractColorChooserPanel colorPanels[] =
      new AbstractColorChooserPanel[] {
        new ListPanel(),
      };
  private JButton button = new JButton("Show Color Chooser");
  private JDialog dialog;

  public void init() {
    Container contentPane = getContentPane();

    contentPane.setLayout(new FlowLayout());
    contentPane.add(button, BorderLayout.CENTER);

    chooser.setChooserPanels(colorPanels);

    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        if(dialog == null) 
          dialog  = JColorChooser.createDialog(
                Test.this, // parent comp
                "Pick A Color",  // dialog title
                false,        // modality
                chooser,    
                null, null);

        dialog.setVisible(true);
      }
    });
  }
  ...
}

The ListPanel class extends abstract ColorChooserPanel class and implements the ListSelectionListener interface. Two panels are created, one for the "Red", "Green", and "Blue" labels and another for their associated lists. Additionally, three default list models are created for each of the lists, and a boolean isAdjustingValue is set to false.

...
class ListPanel extends AbstractColorChooserPanel 
                 implements ListSelectionListener {
  private JPanel labelPanel = new JPanel(),
          listPanel = new JPanel();

  private JList redList = new JList(), blueList = new JList(), 
         greenList = new JList();

  private DefaultListModel redModel = new DefaultListModel(),
               blueModel = new DefaultListModel(),
               greenModel = new DefaultListModel();

  private boolean isAdjusting = false;
  ...

The buildChooser method populates each of the lists with strings representing values from 0 to 256. The lists are added to the list panel, the labels are added to the label panel, and the list and label panels are added to the chooser panel.

Each of the lists has the chooser panel specified as a list selection listener. When a value changes in a list, the chooser panel's valueChanged method retrieves the values from the lists and updates the chooser's selection model accordingly.

  ...
  protected void buildChooser() {
    redList.setFixedCellWidth(50);
    greenList.setFixedCellWidth(50);
    blueList.setFixedCellWidth(50);

    for(int i=0; i < 256; ++i) {
      redModel.addElement(Integer.toString(i));
      greenModel.addElement(Integer.toString(i));
      blueModel.addElement(Integer.toString(i));
    }

    redList.setModel(redModel);
    greenList.setModel(greenModel);
    blueList.setModel(blueModel);

    listPanel.setLayout(new GridLayout(0,3,10,0));

    listPanel.add(new JScrollPane(redList));
    listPanel.add(new JScrollPane(blueList));
    listPanel.add(new JScrollPane(greenList));

    labelPanel.setLayout(new GridLayout(0,3,10,0));

    labelPanel.add(new JLabel("Red"));
    labelPanel.add(new JLabel("Blue"));
    labelPanel.add(new JLabel("Green"));

    setLayout(new BorderLayout());
    add(labelPanel, BorderLayout.NORTH);
    add(listPanel, BorderLayout.CENTER);

    redList.addListSelectionListener(this);
    greenList.addListSelectionListener(this);
    blueList.addListSelectionListener(this);
  }
  public void valueChanged(ListSelectionEvent e) {
    int r = redList.getSelectedIndex(),
      b = blueList.getSelectedIndex(),
      g = greenList.getSelectedIndex();

    if(r != -1 && g != -1 && b != -1)
      getColorSelectionModel().setSelectedColor(
                      new Color(r,g,b));
  }
  ...

The updateChooser method updates the selected values in the lists, depending upon the current color from the chooser's selection model.

The isAdjusting boolean variable is used in order to avoid an infinite loop when JList.setSelectedIndex() is called. The gory details are enumerated below.

A call to JList.setSelectedIndex() causes the list to fire a list selection event, resulting in a call to ListPanel.valueChanged()—recall that ListPanel adds itself as a listener for each list. valueChanged() updates the chooser's selection model, causing ListPanel.updateChooser() to be invoked, and updateChooser invokes JList.setSelectedIndex().

  ...
  public void updateChooser() {
    if( ! isAdjusting) {
      isAdjusting = true;

      Color color = getColorFromModel();
      int r = color.getRed(), g = color.getGreen(), 
        b = color.getBlue();

      redList.setSelectedIndex(r);
      redList.ensureIndexIsVisible(r);

      blueList.setSelectedIndex(b);
      blueList.ensureIndexIsVisible(b);

      greenList.setSelectedIndex(g);
      greenList.ensureIndexIsVisible(g);

      isAdjusting = false;
    }
  }
  ...

The getDisplayName, getSmallDisplayIcon, and getLargeDisplayIcon methods must be implemented by the ListPanel class because they are defined as abstract in AbstractColorChooserPanel. The get...Icon methods return null references because the icons are currently not used within Swing. The getDisplayName method returns a non-null string that would normally be used as the string displayed in the tab associated with the chooser panel. However, because the ListPanel instance is the only chooser panel displayed in the color chooser, the string returned from getDisplayName is not used.

  ...
  public String getDisplayName() {
    return "lists";
  }
  public Icon getSmallDisplayIcon() {
    return null;
  }
  public Icon getLargeDisplayIcon() {
    return null;
  }
}

The applet shown in Figure 16-14 is listed in its entirety in Example 16-12.

Example 16-12 Implementing a Custom Color Chooser Panel

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.colorchooser.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JApplet {
  private JColorChooser chooser = new JColorChooser();
  private AbstractColorChooserPanel colorPanels[] =
      new AbstractColorChooserPanel[] {
        new ListPanel(),
      };
  private JButton button = new JButton("Show Color Chooser");
  private JDialog dialog;

  public void init() {
    Container contentPane = getContentPane();

    contentPane.setLayout(new FlowLayout());
    contentPane.add(button, BorderLayout.CENTER);

    chooser.setChooserPanels(colorPanels);

    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        if(dialog == null) 
          dialog  = JColorChooser.createDialog(
                Test.this, // parent comp
                "Pick A Color",  // dialog title
                false,        // modality
                chooser,    
                null, null);

        dialog.setVisible(true);
      }
    });
  }
}
class ListPanel extends AbstractColorChooserPanel 
        implements ListSelectionListener {
  private JPanel labelPanel = new JPanel(),
          listPanel = new JPanel();

  private JList redList = new JList(), blueList = new JList(), 
         greenList = new JList();

  private DefaultListModel redModel = new DefaultListModel(),
               blueModel = new DefaultListModel(),
               greenModel = new DefaultListModel();

  private boolean isAdjusting = false;

  public void updateChooser() {
    if( ! isAdjusting) {
      isAdjusting = true;

      Color color = getColorFromModel();
      int r = color.getRed(), g = color.getGreen(), 
        b = color.getBlue();

      redList.setSelectedIndex(r);
      redList.ensureIndexIsVisible(r);

      blueList.setSelectedIndex(b);
      blueList.ensureIndexIsVisible(b);

      greenList.setSelectedIndex(g);
      greenList.ensureIndexIsVisible(g);

      isAdjusting = false;
    }
  }
  protected void buildChooser() {
    redList.setFixedCellWidth(50);
    greenList.setFixedCellWidth(50);
    blueList.setFixedCellWidth(50);

    for(int i=0; i < 256; ++i) {
      redModel.addElement(Integer.toString(i));
      greenModel.addElement(Integer.toString(i));
      blueModel.addElement(Integer.toString(i));
    }

    redList.setModel(redModel);
    greenList.setModel(greenModel);
    blueList.setModel(blueModel);

    listPanel.setLayout(new GridLayout(0,3,10,0));

    listPanel.add(new JScrollPane(redList));
    listPanel.add(new JScrollPane(blueList));
    listPanel.add(new JScrollPane(greenList));

    labelPanel.setLayout(new GridLayout(0,3,10,0));

    labelPanel.add(new JLabel("Red"));
    labelPanel.add(new JLabel("Blue"));
    labelPanel.add(new JLabel("Green"));

    setLayout(new BorderLayout());
    add(labelPanel, BorderLayout.NORTH);
    add(listPanel, BorderLayout.CENTER);

    redList.addListSelectionListener(this);
    greenList.addListSelectionListener(this);
    blueList.addListSelectionListener(this);
  }
  public void valueChanged(ListSelectionEvent e) {
    int r = redList.getSelectedIndex(),
      b = blueList.getSelectedIndex(),
      g = greenList.getSelectedIndex();

    if(r != -1 && g != -1 && b != -1)
      getColorSelectionModel().setSelectedColor(
                      new Color(r,g,b));
  }
  public String getDisplayName() {
    return "display name";
  }
  public Icon getSmallDisplayIcon() {
    return null;
  }
  public Icon getLargeDisplayIcon() {
    return null;
  }
}

The JColorChooser class is summarized in Component Summary 16-2.

Component Summary 16-2 JColorChooser

Model(s)

javax.swing.colorchooser.ColorSelectionModel

UI Delegate(s)

javax.swing.plaf.basic.BasicColorChooserUI

Renderer(s)

——

Editor(s)

——

Events Fired

ActionEvents / ChangeEvents / PropertyChangeEvents

Replacement For

——

Class Diagrams


Figure 16-15Figure 16-15 JColorChooser Class Diagram


JColorChooser extends JComponent and implements the Accessible interface. JColorChooser maintains protected references to its preview panel—an instance of JComponent and an array of color chooser panels—objects that implement the AbstractColorChooserPanel class. Additionally, the JColorChooser class defines a set of public static strings used to represent the properties associated with instances of JColorChooser.

JColorChooser Properties

The properties maintained by the JColorChooser class are listed in Table 16-4.

Table 16-4 JColorChooser Properties

Property Name

Data Type

Property Type13

Access14

Default15

chooserPanels

AbstractColorChooserPanel[]

B

SG

L&F

color

Color

S16

CSG

L&F

previewPanel

JComponent

B

SG

L&F

selectionModel

ColorSelectionModel

B

CSG

L&F


chooserPanels — The panels displayed in a color chooser that are used to select a color.

color — The currently selected color in a color chooser.

previewPanel — A panel that visually communicates the currently selected color. The default preview panel can be replaced with the JColorChooser.setPreviewPanel method. See "Preview Panels" on page 988 for more information concerning replacing the default preview panel.

selectionModel — A selection model that implements the swing.colorchooser.ColorSelectionModel interface. Color chooser selection models fire change events when the currently selected color is modified.

JColorChooser Events

The most commonly handled events for color choosers are action events fired when the non-modal color chooser dialog created by JColorChooser.createDialog() is dismissed. Listeners cannot be specified for the buttons contained in the modal color chooser dialogs created with JColorChooser.showDialog().

Significant events fired by the classes that comprise color choosers are listed in Table 16-5.

Table 16-5 Color Chooser Events

Event

Fired by

Triggers/Handling

Action

JColorChooser

trigger: OK/Cancel buttons

Change

DefaultColor SelectionModel

trigger: color selection, handling: UI delegate sets preview panel's foreground color

Property Change

JColorChooser

handling: UI delegate reacts to preview panel and chooser panel changes


The default color selection model for color choosers fires change events when the selected color is modified. The file chooser's UI delegate reacts to change events from the selection model by setting the preview panel's foreground color to the selected color and repainting the panel.

Color choosers fire property change events when their bound properties are modified. To react to changes in a color chooser's color property, a change listener must be registered with the chooser's selection model, as illustrated in Example 16-9 on page 980.

JColorChooser Class Summaries

The public and protected variables and methods for JColorChooser are listed in Class Summary 15-10.

Class Summary 15-10 JColorChooser

Constants

public static final String CHOOSER_PANELS_PROPERTY
public static final String PREVIEW_PANEL_PROPERTY
public static final String SELECTION_MODEL_PROPERTY

The constants defined by the JColorChooser class identify color chooser properties.

Constructors

public JColorChooser()

public JColorChooser(Color)
public JColorChooser(ColorSelectionModel)

The JColorChooser class provides the three constructors listed above. The no-argument constructor creates a color chooser with an initial color of white. The initial color can also be specified explicitly with the last two constructors listed above by a color or color selection model, respectively.

Methods

Creating and Showing Color Chooser Dialogs

public static JDialog createDialog(Component, String, boolean, JColorChooser, ActionListener, ActionListener)
public static Color showDialog(Component, String, Color)

The static methods listed above can be used to create or show a dialog containing an instance of JColorChooser. The methods are discussed in "Displaying Color Choosers In Dialogs" on page 981.

Chooser Panels

public void addChooserPanel(AbstractColorChooserPanel)
public AbstractColorChooserPanel removeChooserPanel(AbstractColorChooserPanel)

public AbstractColorChooserPanel[] getChooserPanels()
public void setChooserPanels(AbstractColorChooserPanel[])

Color choosers allow total control over the color chooser panels that they display. The first two methods listed above can be used to add and remove panels from the array of color chooser panels maintained by instances of JColorChooser.

The last two methods listed above can be used to access the entire array of color chooser panels and to set the array, respectively. See "Color Chooser Panels" on page 990 for an example of replacing the color chooser panels that reside in a color chooser.

Color and Color Selection Model

public Color getColor()
public void setColor(int colorBits)
public void setColor(int red, int green, int blue)
public void setColor(Color)

public ColorSelectionModel getSelectionModel()
public void setSelectionModel(ColorSelectionModel)

The selected color in a color chooser can be explicitly controlled by the setColor methods listed above. A color can be specified by an integer value whose low-order byte specifies the blue component, followed by the green component in the next byte, and the red component in the high-order byte.

Setting a color chooser's color causes its selection model to fire a change event. See Example 16-9 on page 980 for an example of to a change in a color chooser's color.

JColorChoosers have a color selection model that implements the swing.colorchooser.ColorSelectionModel interface. A color chooser's selection model can be obtained or set after construction with the last two methods listed above.

Preview Panels

public JComponent getPreviewPanel()
public void setPreviewPanel(JComponent)

Color choosers display a preview panel that visually communicates the currently selected color. The standard preview panel can be replaced with the last method listed above.

Accessibility / Pluggable Look and Feel

public AccessibleContext getAccessibleContext()
public ColorChooserUI getUI()
public String getUIClassID()
public void setUI(ColorChooserUI)
public void updateUI()

The methods listed above can be found in most extensions of JComponent. Swing lightweight components can return the class name of their UI delegate and an accessible context that contains accessibility information for the component. The updateUI method is invoked when the component is fitted with a UI delegate.

AWT Compatibility

The AWT does not provide a component analogous to JColorChooser.

  • + Share This
  • 🔖 Save To Your Account