Java/Swing JFC/Color Chooser

Материал из Java эксперт
Версия от 06:40, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Adding a Custom Color Chooser Panel to a JColorChooser Dialog

  
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.colorchooser.AbstractColorChooserPanel;
public class Main {
  public static void main(String[] argv) {
    JColorChooser chooser = new JColorChooser();
    chooser.addChooserPanel(new MyChooserPanel());
  }
}
class MyChooserPanel extends AbstractColorChooserPanel {
  public void buildChooser() {
    setLayout(new GridLayout(0, 3));
    makeAddButton("Red", Color.red);
    makeAddButton("Green", Color.green);
    makeAddButton("Blue", Color.blue);
  }
  public void updateChooser() {
  }
  public String getDisplayName() {
    return "MyChooserPanel";
  }
  public Icon getSmallDisplayIcon() {
    return null;
  }
  public Icon getLargeDisplayIcon() {
    return null;
  }
  private void makeAddButton(String name, Color color) {
    JButton button = new JButton(name);
    button.setBackground(color);
    button.setAction(setColorAction);
    add(button);
  }
  Action setColorAction = new AbstractAction() {
    public void actionPerformed(ActionEvent evt) {
      JButton button = (JButton) evt.getSource();
      getColorSelectionModel().setSelectedColor(button.getBackground());
    }
  };
}





A quick test of the JColorChooser dialog

  
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
public class ColorPicker extends JFrame {
  public ColorPicker() {
    super("JColorChooser Test Frame");
    setSize(200, 100);
    final Container contentPane = getContentPane();
    final JButton go = new JButton("Show JColorChooser");
    go.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        Color c;
        c = JColorChooser.showDialog(((Component) e.getSource())
            .getParent(), "Demo", Color.blue);
        contentPane.setBackground(c);
      }
    });
    contentPane.add(go, BorderLayout.SOUTH);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }
  public static void main(String args[]) {
    ColorPicker cp = new ColorPicker();
    cp.setVisible(true);
  }
}





Choose foreground or background color

   
/*
 * Created on 17.12.2004
 *
 */
/*
This file is part of BORG.
    BORG is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    BORG is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    You should have received a copy of the GNU General Public License
    along with BORG; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
Copyright 2003 by Mike Berger
 */

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;

/**
 * GUI control to easy choose foreground or background color.
 * Indicates color to be stored by its own foreground or background.
 * 
 * @author bsv
 * 
 */
public class JButtonKnowsBgColor extends JButton {
  // colorProperty is ONE color, but can be indicated by fore or back color
  protected Color colorProperty;
  // bg=true means "choosed color is background color"
  // bg=false means "choosed color is foreground color"
  protected boolean bg;
  
  public JButtonKnowsBgColor( String p_text, Color p_color, boolean p_bg ){
    setText( p_text );
    setColorProperty( p_color );
    setBg( p_bg );
    setColorByProperty();
    addActionListener(new ModalListener());
        
  }
  
  public void setColorByProperty(){
    if( isBg() ){
      setBackground( getColorProperty() );
    } else {
      setForeground( getColorProperty() );
    }
  }
  // for testing purposes only
  public static void main(String[] args) {
    JButtonKnowsBgColor jbkbc = new JButtonKnowsBgColor( "choose back", Color.RED, true );
    JButtonKnowsBgColor jbkbc1 = new JButtonKnowsBgColor( "choose fore", Color.BLUE, false );
    JFrame jf = new JFrame();
    jf.setLayout( new BorderLayout() );
    jf.getContentPane().add( jbkbc, BorderLayout.NORTH );
    jf.getContentPane().add( jbkbc1, BorderLayout.CENTER );
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setSize( 100, 200 );
    jf.setVisible(true);
  }
  /**
   * @return Returns the color.
   */
  public Color getColorProperty() {
    return colorProperty;
  }
  /**
   * @param color The color to set.
   */
  public void setColorProperty(Color color) {
    this.colorProperty = color;
  }
  /**
   * @return Returns the bg.
   */
  protected boolean isBg() {
    return bg;
  }
  /**
   * @param bg The bg to set.
   */
  protected void setBg(boolean bg) {
    this.bg = bg;
  }
  private class ModalListener implements ActionListener{
    public void actionPerformed(ActionEvent event){
      Color selected = JColorChooser.showDialog(
        null, 
        isBg()?"Set background":"Set foreground", 
        getColorProperty());
      setColorProperty(selected);
      setColorByProperty();
      }
   }
}





Color Chooser Demo

  
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.colorchooser.ColorSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ColorSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("JColorChooser Popup");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();
    final JLabel label = new JLabel("I Love Swing", JLabel.CENTER);
    label.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 48));
    contentPane.add(label, BorderLayout.SOUTH);
    final JColorChooser colorChooser = new JColorChooser(label
        .getBackground());
    colorChooser.setBorder(BorderFactory
        .createTitledBorder("Pick Foreground Color"));
    ColorSelectionModel model = colorChooser.getSelectionModel();
    ChangeListener changeListener = new ChangeListener() {
      public void stateChanged(ChangeEvent changeEvent) {
        Color newForegroundColor = colorChooser.getColor();
        label.setForeground(newForegroundColor);
      }
    };
    model.addChangeListener(changeListener);
    contentPane.add(colorChooser, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
  }
}





ColorChooser Demo 2

  
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.border.Border;
import javax.swing.colorchooser.AbstractColorChooserPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/*
 * ColorChooserDemo2.java is a 1.4 application that requires these files:
 * CrayonPanel.java images/red.gif images/yellow.gif images/green.gif
 * images/blue.gif
 */
public class ColorChooserDemo2 extends JPanel implements ActionListener,
    ChangeListener {
  public JLabel banner;
  public JColorChooser tcc;
  public ColorChooserDemo2() {
    super(new BorderLayout());
    //Set up banner to use as custom preview panel
    banner = new JLabel("Welcome to the Tutorial Zone!", JLabel.CENTER);
    banner.setForeground(Color.yellow);
    banner.setBackground(Color.blue);
    banner.setOpaque(true);
    banner.setFont(new Font("SansSerif", Font.BOLD, 24));
    banner.setPreferredSize(new Dimension(100, 65));
    JPanel bannerPanel = new JPanel(new BorderLayout());
    bannerPanel.add(banner, BorderLayout.CENTER);
    bannerPanel.setBorder(BorderFactory.createTitledBorder("Banner"));
    //Set up color chooser for setting background color
    JPanel panel = new JPanel(); //use FlowLayout
    JButton bcc = new JButton("Show Color Chooser...");
    bcc.addActionListener(this);
    panel.add(bcc);
    panel.setBorder(BorderFactory
        .createTitledBorder("Choose Background Color"));
    //Set up color chooser for setting text color
    tcc = new JColorChooser();
    tcc.getSelectionModel().addChangeListener(this);
    tcc.setBorder(BorderFactory.createTitledBorder("Choose Text Color"));
    //Remove the preview panel
    tcc.setPreviewPanel(new JPanel());
    //Override the chooser panels with our own
    AbstractColorChooserPanel panels[] = { new CrayonPanel() };
    tcc.setChooserPanels(panels);
    tcc.setColor(banner.getForeground());
    add(bannerPanel, BorderLayout.PAGE_START);
    add(panel, BorderLayout.CENTER);
    add(tcc, BorderLayout.PAGE_END);
  }
  public void actionPerformed(ActionEvent e) {
    Color newColor = JColorChooser.showDialog(ColorChooserDemo2.this,
        "Choose Background Color", banner.getBackground());
    if (newColor != null) {
      banner.setBackground(newColor);
    }
  }
  public void stateChanged(ChangeEvent e) {
    Color newColor = tcc.getColor();
    banner.setForeground(newColor);
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("ColorChooserDemo2");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new ColorChooserDemo2();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application"s GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}
class CrayonPanel extends AbstractColorChooserPanel implements ActionListener {
  JToggleButton redCrayon;
  JToggleButton yellowCrayon;
  JToggleButton greenCrayon;
  JToggleButton blueCrayon;
  public void updateChooser() {
    Color color = getColorFromModel();
    if (Color.red.equals(color)) {
      redCrayon.setSelected(true);
    } else if (Color.yellow.equals(color)) {
      yellowCrayon.setSelected(true);
    } else if (Color.green.equals(color)) {
      greenCrayon.setSelected(true);
    } else if (Color.blue.equals(color)) {
      blueCrayon.setSelected(true);
    }
  }
  protected JToggleButton createCrayon(String name, Border normalBorder) {
    JToggleButton crayon = new JToggleButton();
    crayon.setActionCommand(name);
    crayon.addActionListener(this);
    //Set the image or, if that"s invalid, equivalent text.
    ImageIcon icon = createImageIcon("images/" + name + ".gif");
    if (icon != null) {
      crayon.setIcon(icon);
      crayon.setToolTipText("The " + name + " crayon");
      crayon.setBorder(normalBorder);
    } else {
      crayon.setText("Image not found. This is the " + name + " button.");
      crayon.setFont(crayon.getFont().deriveFont(Font.ITALIC));
      crayon.setHorizontalAlignment(JButton.HORIZONTAL);
      crayon.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    }
    return crayon;
  }
  protected void buildChooser() {
    setLayout(new GridLayout(0, 1));
    ButtonGroup boxOfCrayons = new ButtonGroup();
    Border border = BorderFactory.createEmptyBorder(4, 4, 4, 4);
    redCrayon = createCrayon("red", border);
    boxOfCrayons.add(redCrayon);
    add(redCrayon);
    yellowCrayon = createCrayon("yellow", border);
    boxOfCrayons.add(yellowCrayon);
    add(yellowCrayon);
    greenCrayon = createCrayon("green", border);
    boxOfCrayons.add(greenCrayon);
    add(greenCrayon);
    blueCrayon = createCrayon("blue", border);
    boxOfCrayons.add(blueCrayon);
    add(blueCrayon);
  }
  /** Returns an ImageIcon, or null if the path was invalid. */
  protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = CrayonPanel.class.getResource(path);
    if (imgURL != null) {
      return new ImageIcon(imgURL);
    } else {
      System.err.println("Couldn"t find file: " + path);
      return null;
    }
  }
  public void actionPerformed(ActionEvent e) {
    Color newColor = null;
    String command = ((JToggleButton) e.getSource()).getActionCommand();
    if ("green".equals(command))
      newColor = Color.green;
    else if ("red".equals(command))
      newColor = Color.red;
    else if ("yellow".equals(command))
      newColor = Color.yellow;
    else if ("blue".equals(command))
      newColor = Color.blue;
    getColorSelectionModel().setSelectedColor(newColor);
  }
  public String getDisplayName() {
    return "Crayons";
  }
  public Icon getSmallDisplayIcon() {
    return null;
  }
  public Icon getLargeDisplayIcon() {
    return null;
  }
}





ColorChooser Sample 1

  
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
public class ColorChooserSample {
  public static void main(String args[]) {
    JFrame f = new JFrame("JColorChooser Sample");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = f.getContentPane();
    final JButton button = new JButton("Pick to Change Background");
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        Color initialBackground = button.getBackground();
        Color background = JColorChooser.showDialog(null,
            "JColorChooser Sample", initialBackground);
        if (background != null) {
          button.setBackground(background);
        }
      }
    };
    button.addActionListener(actionListener);
    content.add(button, BorderLayout.CENTER);
    f.setSize(300, 200);
    f.setVisible(true);
  }
}





Creating a JColorChooser Dialog

  
import java.awt.Color;
import javax.swing.JColorChooser;
public class Main {
  public static void main(String[] argv) {
    Color initialColor = Color.red;
    Color newColor = JColorChooser.showDialog(null, "Dialog Title", initialColor);
  }
}





Customizing the Preview Panel of a JColorChooser Dialog

  
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.colorchooser.ColorSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main {
  public static void main(String[] argv) {
    JColorChooser chooser = new JColorChooser();
    final MyPreviewPanel pre = new MyPreviewPanel(chooser);
    chooser.setPreviewPanel(pre);
    
    ColorSelectionModel model = chooser.getSelectionModel();
    model.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent evt) {
        ColorSelectionModel model = (ColorSelectionModel) evt.getSource();
        pre.curColor = model.getSelectedColor();
      }
    });
 
    
  }
}
class MyPreviewPanel extends JComponent {
  Color curColor;
  public MyPreviewPanel(JColorChooser chooser) {
    curColor = chooser.getColor();
    
    setPreferredSize(new Dimension(50, 50));
  }
  public void paint(Graphics g) {
    g.setColor(curColor);
    g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
  }
}





extends AbstractColorChooserPanel

  
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.border.Border;
import javax.swing.colorchooser.AbstractColorChooserPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/*
 * ColorChooserDemo2.java requires these files: CrayonPanel.java images/red.gif
 * images/yellow.gif images/green.gif images/blue.gif
 */
public class ColorChooserDemo2 extends JPanel implements ActionListener,
    ChangeListener {
  public JLabel banner;
  public JColorChooser tcc;
  public ColorChooserDemo2() {
    super(new BorderLayout());
    // Set up banner to use as custom preview panel
    banner = new JLabel("Welcome to the Tutorial Zone!", JLabel.CENTER);
    banner.setForeground(Color.yellow);
    banner.setBackground(Color.blue);
    banner.setOpaque(true);
    banner.setFont(new Font("SansSerif", Font.BOLD, 24));
    banner.setPreferredSize(new Dimension(100, 65));
    JPanel bannerPanel = new JPanel(new BorderLayout());
    bannerPanel.add(banner, BorderLayout.CENTER);
    bannerPanel.setBorder(BorderFactory.createTitledBorder("Banner"));
    // Set up color chooser for setting background color
    JPanel panel = new JPanel(); // use FlowLayout
    JButton bcc = new JButton("Show Color Chooser...");
    bcc.addActionListener(this);
    panel.add(bcc);
    panel
        .setBorder(BorderFactory.createTitledBorder("Choose Background Color"));
    // Set up color chooser for setting text color
    tcc = new JColorChooser();
    tcc.getSelectionModel().addChangeListener(this);
    tcc.setBorder(BorderFactory.createTitledBorder("Choose Text Color"));
    // Remove the preview panel
    tcc.setPreviewPanel(new JPanel());
    // Override the chooser panels with our own
    AbstractColorChooserPanel panels[] = { new CrayonPanel() };
    tcc.setChooserPanels(panels);
    tcc.setColor(banner.getForeground());
    add(bannerPanel, BorderLayout.PAGE_START);
    add(panel, BorderLayout.CENTER);
    add(tcc, BorderLayout.PAGE_END);
  }
  public void actionPerformed(ActionEvent e) {
    Color newColor = JColorChooser.showDialog(ColorChooserDemo2.this,
        "Choose Background Color", banner.getBackground());
    if (newColor != null) {
      banner.setBackground(newColor);
    }
  }
  public void stateChanged(ChangeEvent e) {
    Color newColor = tcc.getColor();
    banner.setForeground(newColor);
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    // Create and set up the window.
    JFrame frame = new JFrame("ColorChooserDemo2");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Create and set up the content pane.
    JComponent newContentPane = new ColorChooserDemo2();
    newContentPane.setOpaque(true); // content panes must be opaque
    frame.setContentPane(newContentPane);
    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application"s GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *  - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *  - Neither the name of Sun Microsystems nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
class CrayonPanel extends AbstractColorChooserPanel implements ActionListener {
  JToggleButton redCrayon;
  JToggleButton yellowCrayon;
  JToggleButton greenCrayon;
  JToggleButton blueCrayon;
  public void updateChooser() {
    Color color = getColorFromModel();
    if (Color.red.equals(color)) {
      redCrayon.setSelected(true);
    } else if (Color.yellow.equals(color)) {
      yellowCrayon.setSelected(true);
    } else if (Color.green.equals(color)) {
      greenCrayon.setSelected(true);
    } else if (Color.blue.equals(color)) {
      blueCrayon.setSelected(true);
    }
  }
  protected JToggleButton createCrayon(String name, Border normalBorder) {
    JToggleButton crayon = new JToggleButton();
    crayon.setActionCommand(name);
    crayon.addActionListener(this);
    // Set the image or, if that"s invalid, equivalent text.
    ImageIcon icon = createImageIcon("images/" + name + ".gif");
    if (icon != null) {
      crayon.setIcon(icon);
      crayon.setToolTipText("The " + name + " crayon");
      crayon.setBorder(normalBorder);
    } else {
      crayon.setText("Image not found. This is the " + name + " button.");
      crayon.setFont(crayon.getFont().deriveFont(Font.ITALIC));
      crayon.setHorizontalAlignment(JButton.HORIZONTAL);
      crayon.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    }
    return crayon;
  }
  protected void buildChooser() {
    setLayout(new GridLayout(0, 1));
    ButtonGroup boxOfCrayons = new ButtonGroup();
    Border border = BorderFactory.createEmptyBorder(4, 4, 4, 4);
    redCrayon = createCrayon("red", border);
    boxOfCrayons.add(redCrayon);
    add(redCrayon);
    yellowCrayon = createCrayon("yellow", border);
    boxOfCrayons.add(yellowCrayon);
    add(yellowCrayon);
    greenCrayon = createCrayon("green", border);
    boxOfCrayons.add(greenCrayon);
    add(greenCrayon);
    blueCrayon = createCrayon("blue", border);
    boxOfCrayons.add(blueCrayon);
    add(blueCrayon);
  }
  /** Returns an ImageIcon, or null if the path was invalid. */
  protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = CrayonPanel.class.getResource(path);
    if (imgURL != null) {
      return new ImageIcon(imgURL);
    } else {
      System.err.println("Couldn"t find file: " + path);
      return null;
    }
  }
  public void actionPerformed(ActionEvent e) {
    Color newColor = null;
    String command = ((JToggleButton) e.getSource()).getActionCommand();
    if ("green".equals(command))
      newColor = Color.green;
    else if ("red".equals(command))
      newColor = Color.red;
    else if ("yellow".equals(command))
      newColor = Color.yellow;
    else if ("blue".equals(command))
      newColor = Color.blue;
    getColorSelectionModel().setSelectedColor(newColor);
  }
  public String getDisplayName() {
    return "Crayons";
  }
  public Icon getSmallDisplayIcon() {
    return null;
  }
  public Icon getLargeDisplayIcon() {
    return null;
  }
}





Getting and Setting the Selected Color in a JColorChooser Dialog

  
import java.awt.Color;
import javax.swing.JColorChooser;
public class Main {
  public static void main(String[] argv) {
    JColorChooser chooser = new JColorChooser();
    // Set the selected color
    chooser.setColor(Color.red);
    // Get current selected color
    Color color = chooser.getColor();
  }
}





JColorChooser demo

  
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
public class ColorChooserDemo extends JFrame {
  public ColorChooserDemo() {
    super();
    createUI();
    setVisible(true);
  }
  protected void createUI() {
    setSize(400, 400);
    getContentPane().setLayout(new GridBagLayout());
    JButton colorButton = new JButton("Choose a color...");
    getContentPane().add(colorButton);
    colorButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        Color c = JColorChooser.showDialog(ColorChooserDemo.this,
            "Choose a color...", getBackground());
        if (c != null)
          getContentPane().setBackground(c);
      }
    });
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent we) {
        System.exit(0);
      }
    });
  }
  public static void main(String[] args) {
    new ColorChooserDemo();
  }
  
}





JColorChooser dialog with a custom preview pane.

  
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly 
*/
// ColorPicker3.java
//A quick test of the JColorChooser dialog. This example adds a custom
//preview pane.
//
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.colorchooser.AbstractColorChooserPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ColorPicker3 extends JFrame {
  Color c;
  public ColorPicker3() {
    super("JColorChooser Test Frame");
    setSize(200, 100);
    final JButton go = new JButton("Show JColorChoser");
    final Container contentPane = getContentPane();
    go.addActionListener(new ActionListener() {
      final JColorChooser chooser = new JColorChooser();
      boolean first = true;
      public void actionPerformed(ActionEvent e) {
        if (first) {
          first = false;
          GrayScalePanel gsp = new GrayScalePanel();
          chooser.addChooserPanel(gsp);
          chooser.setPreviewPanel(new CustomPane());
        }
        JDialog dialog = JColorChooser.createDialog(ColorPicker3.this,
            "Demo 3", true, chooser, new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                c = chooser.getColor();
              }
            }, null);
        dialog.setVisible(true);
        contentPane.setBackground(c);
      }
    });
    contentPane.add(go, BorderLayout.SOUTH);
    // addWindowListener(new BasicWindowMonitor()); // 1.1 & 1.2
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }
  public class CustomPane extends JPanel {
    JLabel j1 = new JLabel("This is a custom preview pane", JLabel.CENTER);
    JLabel j2 = new JLabel("This label previews the background",
        JLabel.CENTER);
    public CustomPane() {
      super(new GridLayout(0, 1));
      j2.setOpaque(true);
      add(j1);
      add(j2);
    }
    public void setForeground(Color c) {
      super.setForeground(c);
      if (j1 != null) {
        j1.setForeground(c);
        j2.setBackground(c);
      }
    }
  }
  public static void main(String args[]) {
    ColorPicker3 cp3 = new ColorPicker3();
    cp3.setVisible(true);
  }
}
//GrayScalePanel.java
//A simple implementation of the AbstractColorChooserPanel class. This class
//provides a slider and a textfield for picking out a shade of gray.
//
class GrayScalePanel extends AbstractColorChooserPanel implements
    ChangeListener, ActionListener {
  JSlider scale;
  JTextField percentField;
  // Set up our list of grays. We"ll assume we have all 256 possible shades,
  // and we"ll do it when the class is loaded.
  static Color[] grays = new Color[256];
  static {
    for (int i = 0; i < 256; i++) {
      grays[i] = new Color(i, i, i);
    }
  }
  public GrayScalePanel() {
    setLayout(new GridLayout(0, 1));
    // create the slider and attach us as a listener
    scale = new JSlider(JSlider.HORIZONTAL, 0, 255, 128);
    scale.addChangeListener(this);
    // Set up our display for the chooser
    add(new JLabel("Pick your shade of gray:", JLabel.CENTER));
    JPanel jp = new JPanel();
    jp.add(new JLabel("Black"));
    jp.add(scale);
    jp.add(new JLabel("White"));
    add(jp);
    JPanel jp2 = new JPanel();
    percentField = new JTextField(3);
    percentField.setHorizontalAlignment(SwingConstants.RIGHT);
    percentField.addActionListener(this);
    jp2.add(percentField);
    jp2.add(new JLabel("%"));
    add(jp2);
  }
  // We did this work in the constructor so we can skip it here.
  protected void buildChooser() {
  }
  // Make sure the slider is in sync with the other panels.
  public void updateChooser() {
    Color c = getColorSelectionModel().getSelectedColor();
    scale.setValue(toGray(c));
  }
  protected int toGray(Color c) {
    int r = c.getRed();
    int g = c.getGreen();
    int b = c.getBlue();
    // Grab the luminance the same way GIMP does...
    return (int) Math.round(0.3 * r + 0.59 * g + 0.11 * b);
  }
  // Pick a name for our tab in the chooser
  public String getDisplayName() {
    return "Gray Scale";
  }
  // No need for an icon.
  public Icon getSmallDisplayIcon() {
    return null;
  }
  public Icon getLargeDisplayIcon() {
    return null;
  }
  // And lastly, update the selection model as our slider changes.
  public void stateChanged(ChangeEvent ce) {
    getColorSelectionModel().setSelectedColor(grays[scale.getValue()]);
    percentField.setText(""
        + (100 - (int) Math.round(scale.getValue() / 2.55)));
  }
  public void actionPerformed(ActionEvent ae) {
    int val = 100 - Integer.parseInt(ae.getActionCommand());
    getColorSelectionModel().setSelectedColor(grays[(int) (val * 2.55)]);
  }
}





JColorChooser dialog with the custom GrayScalePanel picker tab.

  
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly 
*/
// ColorPicker2.java
//A quick test of the JColorChooser dialog. This one installs the custom
//GrayScalePanel picker tab.
//
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.colorchooser.AbstractColorChooserPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ColorPicker2 extends JFrame {
  Color c;
  public ColorPicker2() {
    super("JColorChooser Test Frame");
    setSize(200, 100);
    final JButton go = new JButton("Show JColorChoser");
    final Container contentPane = getContentPane();
    go.addActionListener(new ActionListener() {
      final JColorChooser chooser = new JColorChooser();
      boolean first = true;
      public void actionPerformed(ActionEvent e) {
        if (first) {
          first = false;
          GrayScalePanel gsp = new GrayScalePanel();
          chooser.addChooserPanel(gsp);
        }
        JDialog dialog = JColorChooser.createDialog(ColorPicker2.this,
            "Demo 2", true, chooser, new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                c = chooser.getColor();
              }
            }, null);
        dialog.setVisible(true);
        contentPane.setBackground(c);
      }
    });
    contentPane.add(go);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }
  public static void main(String args[]) {
    ColorPicker2 cp2 = new ColorPicker2();
    cp2.setVisible(true);
  }
}
//GrayScalePanel.java
//A simple implementation of the AbstractColorChooserPanel class. This class
//provides a slider and a textfield for picking out a shade of gray.
//
class GrayScalePanel extends AbstractColorChooserPanel implements
    ChangeListener, ActionListener {
  JSlider scale;
  JTextField percentField;
  // Set up our list of grays. We"ll assume we have all 256 possible shades,
  // and we"ll do it when the class is loaded.
  static Color[] grays = new Color[256];
  static {
    for (int i = 0; i < 256; i++) {
      grays[i] = new Color(i, i, i);
    }
  }
  public GrayScalePanel() {
    setLayout(new GridLayout(0, 1));
    // create the slider and attach us as a listener
    scale = new JSlider(JSlider.HORIZONTAL, 0, 255, 128);
    scale.addChangeListener(this);
    // Set up our display for the chooser
    add(new JLabel("Pick your shade of gray:", JLabel.CENTER));
    JPanel jp = new JPanel();
    jp.add(new JLabel("Black"));
    jp.add(scale);
    jp.add(new JLabel("White"));
    add(jp);
    JPanel jp2 = new JPanel();
    percentField = new JTextField(3);
    percentField.setHorizontalAlignment(SwingConstants.RIGHT);
    percentField.addActionListener(this);
    jp2.add(percentField);
    jp2.add(new JLabel("%"));
    add(jp2);
  }
  // We did this work in the constructor so we can skip it here.
  protected void buildChooser() {
  }
  // Make sure the slider is in sync with the other panels.
  public void updateChooser() {
    Color c = getColorSelectionModel().getSelectedColor();
    scale.setValue(toGray(c));
  }
  protected int toGray(Color c) {
    int r = c.getRed();
    int g = c.getGreen();
    int b = c.getBlue();
    // Grab the luminance the same way GIMP does...
    return (int) Math.round(0.3 * r + 0.59 * g + 0.11 * b);
  }
  // Pick a name for our tab in the chooser
  public String getDisplayName() {
    return "Gray Scale";
  }
  // No need for an icon.
  public Icon getSmallDisplayIcon() {
    return null;
  }
  public Icon getLargeDisplayIcon() {
    return null;
  }
  // And lastly, update the selection model as our slider changes.
  public void stateChanged(ChangeEvent ce) {
    getColorSelectionModel().setSelectedColor(grays[scale.getValue()]);
    percentField.setText(""
        + (100 - (int) Math.round(scale.getValue() / 2.55)));
  }
  public void actionPerformed(ActionEvent ae) {
    int val = 100 - Integer.parseInt(ae.getActionCommand());
    getColorSelectionModel().setSelectedColor(grays[(int) (val * 2.55)]);
  }
}





Listening for Changes to the Selected Color in a JColorChooser Dialog

  
import java.awt.Color;
import javax.swing.JColorChooser;
import javax.swing.colorchooser.ColorSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main {
  public static void main(String[] argv) {
    JColorChooser chooser = new JColorChooser();
    ColorSelectionModel model = chooser.getSelectionModel();
    model.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent evt) {
        ColorSelectionModel model = (ColorSelectionModel) evt.getSource();
        Color newColor = model.getSelectedColor();
      }
    });
  }
}





Listening for OK and Cancel Events in a JColorChooser Dialog

  
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
public class Main {
  public static void main(String[] argv) {
    final JColorChooser chooser = new JColorChooser();
    ActionListener okListener = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        Color newColor = chooser.getColor();
      }
    };
    ActionListener cancelListener = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        Color newColor = chooser.getColor();
      }
    };
    boolean modal = false;
    JDialog dialog = JColorChooser.createDialog(null, "Dialog Title", modal, chooser, okListener,
        cancelListener);
    dialog.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent evt) {
        Color newColor = chooser.getColor();
      }
    });
  }
}





Preview pane simply displays the currently selected color.

  
class MyPreviewPane extends JLabel{
  Color curColor;
  public MyPreviewPane(JColorChooser chooser) {
    curColor = chooser.getColor();
    ColorSelectionModel model = chooser.getSelectionModel();
    model.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent evt) {
        ColorSelectionModel model = (ColorSelectionModel) evt.getSource();
        curColor = model.getSelectedColor();
      }
    });
    setPreferredSize(new Dimension(50, 50));
  }
  public void paint(Graphics g) {
    g.setColor(curColor);
    g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
  }
}





Removing a Color Chooser Panel from a JColorChooser Dialog

  
import javax.swing.JColorChooser;
import javax.swing.colorchooser.AbstractColorChooserPanel;
public class Main {
  public static void main(String[] argv) {
    JColorChooser chooser = new JColorChooser();
    AbstractColorChooserPanel[] oldPanels = chooser.getChooserPanels();
    for (int i = 0; i < oldPanels.length; i++) {
      String clsName = oldPanels[i].getClass().getName();
      if (clsName.equals("javax.swing.colorchooser.DefaultSwatchChooserPanel")) {
        chooser.removeChooserPanel(oldPanels[i]);
      } else if (clsName.equals("javax.swing.colorchooser.DefaultRGBChooserPanel")) {
        chooser.removeChooserPanel(oldPanels[i]);
      } else if (clsName.equals("javax.swing.colorchooser.DefaultHSBChooserPanel")) {
        chooser.removeChooserPanel(oldPanels[i]);
      }
    }
  }
}





Removing the Preview Panel from a JColorChooser Dialog

  
import javax.swing.JColorChooser;
import javax.swing.JPanel;
public class Main {
  public static void main(String[] argv) {
    JColorChooser chooser = new JColorChooser();
    chooser.setPreviewPanel(new JPanel());
  }
}





Retrieving the Color Chooser Panels in a JColorChooser Dialog

  
import javax.swing.JColorChooser;
import javax.swing.colorchooser.AbstractColorChooserPanel;
public class Main {
  public static void main(String[] argv) {
    JColorChooser chooser = new JColorChooser();
    findPanel(chooser, "javax.swing.colorchooser.DefaultSwatchChooserPanel");
    findPanel(chooser, "javax.swing.colorchooser.DefaultHSBChooserPanel");
    findPanel(chooser, "javax.swing.colorchooser.DefaultRGBChooserPanel");
  }
  public static AbstractColorChooserPanel findPanel(JColorChooser chooser, String name) {
    AbstractColorChooserPanel[] panels = chooser.getChooserPanels();
    for (int i = 0; i < panels.length; i++) {
      String clsName = panels[i].getClass().getName();
      if (clsName.equals(name)) {
        return panels[i];
      }
    }
    return null;
  }
}





Setting the Order of the Color Chooser Panel Tabs in a JColorChooser Dialog

  
import javax.swing.JColorChooser;
import javax.swing.colorchooser.AbstractColorChooserPanel;
public class Main {
  public static void main(String[] argv) {
    JColorChooser chooser = new JColorChooser();
    int numPanels = chooser.getChooserPanels().length;
    AbstractColorChooserPanel[] newPanels = new AbstractColorChooserPanel[numPanels];
    newPanels[0] = findPanel(chooser, "javax.swing.colorchooser.DefaultHSBChooserPanel");
    newPanels[1] = findPanel(chooser, "javax.swing.colorchooser.DefaultRGBChooserPanel");
    newPanels[2] = findPanel(chooser, "javax.swing.colorchooser.DefaultSwatchChooserPanel");
    chooser.setChooserPanels(newPanels);
  }
  public static AbstractColorChooserPanel findPanel(JColorChooser chooser, String name) {
    AbstractColorChooserPanel[] panels = chooser.getChooserPanels();
    for (int i = 0; i < panels.length; i++) {
      String clsName = panels[i].getClass().getName();
      if (clsName.equals(name)) {
        return panels[i];
      }
    }
    return null;
  }
}





Swing ColorChooser Demo

  
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/* SwingColorChooserDemo.java is a 1.4 application that requires no other files. */
public class SwingColorChooserDemo extends JPanel implements ChangeListener {
  protected JColorChooser tcc;
  protected JLabel banner;
  public SwingColorChooserDemo() {
    super(new BorderLayout());
    //Set up the banner at the top of the window
    banner = new JLabel("Welcome to the Tutorial Zone!", JLabel.CENTER);
    banner.setForeground(Color.yellow);
    banner.setBackground(Color.blue);
    banner.setOpaque(true);
    banner.setFont(new Font("SansSerif", Font.BOLD, 24));
    banner.setPreferredSize(new Dimension(100, 65));
    JPanel bannerPanel = new JPanel(new BorderLayout());
    bannerPanel.add(banner, BorderLayout.CENTER);
    bannerPanel.setBorder(BorderFactory.createTitledBorder("Banner"));
    //Set up color chooser for setting text color
    tcc = new JColorChooser(banner.getForeground());
    tcc.getSelectionModel().addChangeListener(this);
    tcc.setBorder(BorderFactory.createTitledBorder("Choose Text Color"));
    add(bannerPanel, BorderLayout.CENTER);
    add(tcc, BorderLayout.PAGE_END);
  }
  public void stateChanged(ChangeEvent e) {
    Color newColor = tcc.getColor();
    banner.setForeground(newColor);
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("SwingColorChooserDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new SwingColorChooserDemo();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application"s GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}





System Color Chooser

  
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.colorchooser.AbstractColorChooserPanel;
import javax.swing.colorchooser.ColorSelectionModel;
public class CustomPanelPopup {
  public static void main(String args[]) {
    JFrame frame = new JFrame("JColorChooser Custom Panel Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();
    final JButton button = new JButton("Pick to Change Background");
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        Color initialBackground = button.getBackground();
        final JColorChooser colorChooser = new JColorChooser(
            initialBackground);
        SystemColorChooserPanel newChooser = new SystemColorChooserPanel();
        //        AbstractColorChooserPanel chooserPanels[] = {newChooser};
        //        colorChooser.setChooserPanels(chooserPanels);
        colorChooser.addChooserPanel(newChooser);
        // For okay button selection, change button background to
        // selected color
        ActionListener okActionListener = new ActionListener() {
          public void actionPerformed(ActionEvent actionEvent) {
            Color newColor = colorChooser.getColor();
            if (newColor.equals(button.getForeground())) {
              System.out.println("Color change rejected");
            } else {
              button.setBackground(colorChooser.getColor());
            }
          }
        };
        // For cancel button selection, change button background to red
        ActionListener cancelActionListener = new ActionListener() {
          public void actionPerformed(ActionEvent actionEvent) {
            button.setBackground(Color.red);
          }
        };
        final JDialog dialog = JColorChooser.createDialog(null,
            "Change Button Background", true, colorChooser,
            okActionListener, cancelActionListener);
        // Wait until current event dispatching completes before showing
        // dialog
        Runnable showDialog = new Runnable() {
          public void run() {
            dialog.show();
          }
        };
        SwingUtilities.invokeLater(showDialog);
      }
    };
    button.addActionListener(actionListener);
    contentPane.add(button, BorderLayout.CENTER);
    frame.setSize(300, 100);
    frame.setVisible(true);
  }
}
class SystemColorChooserPanel extends AbstractColorChooserPanel implements
    ItemListener {
  private static int NOT_FOUND = -1;
  JComboBox comboBox;
  String labels[] = { "black", "blue", "cyan", "darkGray", "gray", "green",
      "lightGray", "magenta", "orange", "pink", "red", "white", "yellow",
      "activeCaption", "activeCaptionBorder", "activeCaptionText",
      "control", "controlDkShadow", "controlHighlight",
      "controlLtHighlight", "controlShadow", "controlText", "desktop",
      "inactiveCaption", "inactiveCaptionBorder", "inactiveCaptionText",
      "info", "infoText", "menu", "menuText", "scrollbar", "text",
      "textHighlight", "textHighlightText", "textInactiveText",
      "textText", "window", "windowBorder", "windowText", "<Custom>" };
  Color colors[] = { Color.black, Color.blue, Color.cyan, Color.darkGray,
      Color.gray, Color.green, Color.lightGray, Color.magenta,
      Color.orange, Color.pink, Color.red, Color.white, Color.yellow,
      SystemColor.activeCaption, SystemColor.activeCaptionBorder,
      SystemColor.activeCaptionText, SystemColor.control,
      SystemColor.controlDkShadow, SystemColor.controlHighlight,
      SystemColor.controlLtHighlight, SystemColor.controlShadow,
      SystemColor.controlText, SystemColor.desktop,
      SystemColor.inactiveCaption, SystemColor.inactiveCaptionBorder,
      SystemColor.inactiveCaptionText, SystemColor.info,
      SystemColor.infoText, SystemColor.menu, SystemColor.menuText,
      SystemColor.scrollbar, SystemColor.text, SystemColor.textHighlight,
      SystemColor.textHighlightText, SystemColor.textInactiveText,
      SystemColor.textText, SystemColor.window, SystemColor.windowBorder,
      SystemColor.windowText, null };
  // Change combo box to match color, if possible
  private void setColor(Color newColor) {
    int position = findColorPosition(newColor);
    comboBox.setSelectedIndex(position);
  }
  // Given a label, find the position of the label in the list
  private int findColorLabel(Object label) {
    String stringLabel = label.toString();
    int position = NOT_FOUND;
    for (int i = 0, n = labels.length; i < n; i++) {
      if (stringLabel.equals(labels[i])) {
        position = i;
        break;
      }
    }
    return position;
  }
  // Given a color, find the position whose color matches
  // This could result in a position different from original if two are equal
  // Since color is same, this is considered to be okay
  private int findColorPosition(Color color) {
    int position = colors.length - 1;
    // Cannot use equals() to compare Color and SystemColor
    int colorRGB = color.getRGB();
    for (int i = 0, n = colors.length; i < n; i++) {
      if ((colors[i] != null) && (colorRGB == colors[i].getRGB())) {
        position = i;
        break;
      }
    }
    return position;
  }
  public void itemStateChanged(ItemEvent itemEvent) {
    int state = itemEvent.getStateChange();
    if (state == ItemEvent.SELECTED) {
      int position = findColorLabel(itemEvent.getItem());
      // last position is bad (not selectable)
      if ((position != NOT_FOUND) && (position != labels.length - 1)) {
        ColorSelectionModel selectionModel = getColorSelectionModel();
        selectionModel.setSelectedColor(colors[position]);
      }
    }
  }
  public String getDisplayName() {
    return "SystemColor";
  }
  public Icon getSmallDisplayIcon() {
    return new DiamondIcon(Color.blue);
  }
  public Icon getLargeDisplayIcon() {
    return new DiamondIcon(Color.green);
  }
  protected void buildChooser() {
    comboBox = new JComboBox(labels);
    comboBox.addItemListener(this);
    add(comboBox);
  }
  public void updateChooser() {
    Color color = getColorFromModel();
    setColor(color);
  }
}
class DiamondIcon implements Icon {
  private Color color;
  private boolean selected;
  private int width;
  private int height;
  private Polygon poly;
  private static final int DEFAULT_WIDTH = 10;
  private static final int DEFAULT_HEIGHT = 10;
  public DiamondIcon(Color color) {
    this(color, true, DEFAULT_WIDTH, DEFAULT_HEIGHT);
  }
  public DiamondIcon(Color color, boolean selected) {
    this(color, selected, DEFAULT_WIDTH, DEFAULT_HEIGHT);
  }
  public DiamondIcon(Color color, boolean selected, int width, int height) {
    this.color = color;
    this.selected = selected;
    this.width = width;
    this.height = height;
    initPolygon();
  }
  private void initPolygon() {
    poly = new Polygon();
    int halfWidth = width / 2;
    int halfHeight = height / 2;
    poly.addPoint(0, halfHeight);
    poly.addPoint(halfWidth, 0);
    poly.addPoint(width, halfHeight);
    poly.addPoint(halfWidth, height);
  }
  public int getIconHeight() {
    return height;
  }
  public int getIconWidth() {
    return width;
  }
  public void paintIcon(Component c, Graphics g, int x, int y) {
    g.setColor(color);
    g.translate(x, y);
    if (selected) {
      g.fillPolygon(poly);
    } else {
      g.drawPolygon(poly);
    }
    g.translate(-x, -y);
  }
}