net.java.dev.colorchooser
Class ColorChooser

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by net.java.dev.colorchooser.ColorChooser
All Implemented Interfaces:
ImageObserver, MenuContainer, Serializable

public final class ColorChooser
extends JComponent

A color chooser which can pop up a pluggable set of palettes. The palette displayed is controlled by combinations of the alt and shift and ctrl (command on macintosh) keys. Will fire an action event when a color is selected. For accessibility, it will show a standard Swing color chooser if focused and either space or enter are pressed.

By default, supports two sets of palettes - a set of 4 continuous palettes and a set of 4 tiled, fixed palettes (the SVG/X palette, Swing/AWT palettes and a history of recently selected colors). Whether the tiled or continuous palettes are given precedence depends on the property continuousPalettePreferred.

Palettes are pluggable, so it is possible to provide your own implementation(s) of Palette to be displayed when the component is clicked.

Typical usage: Attach an ActionListener; it will be notified when the user selects a color.

To catch colors as the user selects, listen for PROP_TRANSIENT_COLOR. The component will fire changes in PROP_COLOR along with actin events, when the user selects a color. PROP_COLOR changes are fired both in response to use actions and programmatic changes to the color property.

See Also:
Serialized Form

Nested Class Summary
 
Nested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
 
Nested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainer
 
Nested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
 
Field Summary
static String PROP_COLOR
          Property name for property fired when the color property changes.
static String PROP_CONTINUOUS_PALETTE
          Fired when the value of the continuous palette changes.
static String PROP_PICKER_VISIBLE
          Property indicating the visibility of the popup palette.
static String PROP_TRANSIENT_COLOR
          Property name for property fired when the transient color property (the color while the user is selecting) changes.
static String UI_CLASS_ID
          UI Class ID under which the UI delegate class is stored in UIManager (see UIManager.getUI()).
 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
ColorChooser()
          Create a color chooser
ColorChooser(Color initialColor)
          Create a color chooser initialized to the passed color, defaulted to show a continuous palette on initial click.
ColorChooser(Palette[] palettes)
          Create a color chooser with the passed array of 8 or fewer palettes.
ColorChooser(Palette[] palettes, Color initialColor)
          Create a color chooser with the passed array of 8 palettes and initialized with the passed color.
 
Method Summary
 void addActionListener(ActionListener listener)
          Registers ActionListener to receive events.
static String colorToString(Color c)
          Get a string representation of a color, if possible returning a named, localized constant if the passed color matches one of the SVG constants; else returning a String representing RGB values.
 Color getColor()
          Get the color currently represented by this component.
static String getColorName(Color color)
          Returns the SVG or Swing constant name for the passed color, if the color exactly matches a color in the Swing UIManager constants or the SVG/X-Windows constants.
 Palette[] getPalettes()
          Get the array of palettes that will be displayed when the user clicks this color chooser component and holds down various keys.
 Color getTransientColor()
          Returns the currently displayed color which may not be the same as the value of getColor() but is the color currently displayed as the user moves the mouse to select the color.
 String getUIClassId()
          Overridden to return UI_CLASS_ID
 boolean isContinuousPalettePreferred()
          Determine whether the initial palette shown when clicked with no keys pressed is one showing a continuous (rainbow) palette or a set of tiles with different colors.
 void removeActionListener(ActionListener listener)
          Removes ActionListener from the list of listeners.
 void setColor(Color c)
          Set the color this color chooser currently represents.
 void setContinuousPalettePreferred(boolean val)
          Set whether the initial palette shown when clicked with no keys pressed is one showing a continuous (rainbow) palette or a set of tiles with different colors.
 void setPalettes(Palette[] palettes)
          Set the Palette objects this color chooser will display.
 void updateUI()
           
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getAccessibleContext, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

UI_CLASS_ID

public static final String UI_CLASS_ID
UI Class ID under which the UI delegate class is stored in UIManager (see UIManager.getUI()). The string value is "nbColorChooserUI"

See Also:
Constant Field Values

PROP_COLOR

public static final String PROP_COLOR
Property name for property fired when the color property changes.

See Also:
Constant Field Values

PROP_TRANSIENT_COLOR

public static final String PROP_TRANSIENT_COLOR
Property name for property fired when the transient color property (the color while the user is selecting) changes.

See Also:
Constant Field Values

PROP_CONTINUOUS_PALETTE

public static final String PROP_CONTINUOUS_PALETTE
Fired when the value of the continuous palette changes.

See Also:
Constant Field Values

PROP_PICKER_VISIBLE

public static final String PROP_PICKER_VISIBLE
Property indicating the visibility of the popup palette. Code that tracks PROP_TRANSIENT_COLOR can listen for this property with a value of false to do a final update using the value from getColor() to ensure the set color is in sync with the actual value of the color picker - in the case that the mouse was released off the palette, the color may be restored to its previous value.

See Also:
Constant Field Values
Constructor Detail

ColorChooser

public ColorChooser()
Create a color chooser


ColorChooser

public ColorChooser(Color initialColor)
Create a color chooser initialized to the passed color, defaulted to show a continuous palette on initial click.


ColorChooser

public ColorChooser(Palette[] palettes,
                    Color initialColor)
Create a color chooser with the passed array of 8 palettes and initialized with the passed color.


ColorChooser

public ColorChooser(Palette[] palettes)
Create a color chooser with the passed array of 8 or fewer palettes.

Method Detail

getUIClassId

public String getUIClassId()
Overridden to return UI_CLASS_ID


updateUI

public void updateUI()
Overrides:
updateUI in class JComponent

getColor

public Color getColor()
Get the color currently represented by this component. If the user is in the process of selecting (the palette or color chooser is open), this will be the last known value, until such time as the user selects a color and an action event is fired.


setColor

public void setColor(Color c)
Set the color this color chooser currently represents. Note this will fire a change in PROP_COLOR but will not trigger an action event to be fired.


getTransientColor

public Color getTransientColor()
Returns the currently displayed color which may not be the same as the value of getColor() but is the color currently displayed as the user moves the mouse to select the color.

Returns:
the color currently being displayed (not necessarily the one returned by getColor()).
See Also:
PROP_TRANSIENT_COLOR, setTransientColor(java.awt.Color)

colorToString

public static String colorToString(Color c)
Get a string representation of a color, if possible returning a named, localized constant if the passed color matches one of the SVG constants; else returning a String representing RGB values.


getColorName

public static String getColorName(Color color)
Returns the SVG or Swing constant name for the passed color, if the color exactly matches a color in the Swing UIManager constants or the SVG/X-Windows constants.


setContinuousPalettePreferred

public void setContinuousPalettePreferred(boolean val)
Set whether the initial palette shown when clicked with no keys pressed is one showing a continuous (rainbow) palette or a set of tiles with different colors.

Parameters:
val - The value, true to show a continuous palette by default

isContinuousPalettePreferred

public boolean isContinuousPalettePreferred()
Determine whether the initial palette shown when clicked with no keys pressed is one showing a continuous (rainbow) palette or a set of tiles with different colors. The default is TRUE.

Returns:
whether or not to default to a continuous palette

setPalettes

public void setPalettes(Palette[] palettes)
Set the Palette objects this color chooser will display. Can be null to reset to defaults. The passed array length must less than or equal to 8.

Which palette is shown to the user depends on what if any control keys are being held when the user initially clicks or presses while dragging the mouse to select. The mapping between key combinations and palette entries is:


getPalettes

public Palette[] getPalettes()
Get the array of palettes that will be displayed when the user clicks this color chooser component and holds down various keys.


addActionListener

public void addActionListener(ActionListener listener)
Registers ActionListener to receive events. Action events are fired when the user selects a color, either by click-drag-releasing the mouse over the popup palette, or by pressing space or enter and selecting a color from the popup JColorChooser.

Parameters:
listener - The listener to register.

removeActionListener

public void removeActionListener(ActionListener listener)
Removes ActionListener from the list of listeners. Action events are fired when the user selects a color, either by click-drag-releasing the mouse over the popup palette, or by pressing space or enter and selecting a color from the popup JColorChooser (note they are not fired if you call setColor()).

Parameters:
listener - The listener to remove.