Java Swing | JColorChooser Class

26 Jul, 2021
JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color. This class provides three levels of API:
A static convenience method that shows a modal color-chooser dialog and returns the color selected by the user.A static convenience method for creating a color-chooser dialog where ActionListeners can be specified to be invoked when the user presses one of the dialog buttons.The ability to create instances of JColorChooser panes directly (within any container). PropertyChange listeners can be added to detect when the current “color” property changes.
A static convenience method that shows a modal color-chooser dialog and returns the color selected by the user.
A static convenience method for creating a color-chooser dialog where ActionListeners can be specified to be invoked when the user presses one of the dialog buttons.
The ability to create instances of JColorChooser panes directly (within any container). PropertyChange listeners can be added to detect when the current “color” property changes.
Constructors of the class:  
JColorChooser(): Creates a color chooser pane with an initial color of white.JColorChooser(Color initialColor): Creates a color chooser pane with the specified initial color.JColorChooser(ColorSelectionModel model): Creates a color chooser pane with the specified ColorSelectionModel.
JColorChooser(): Creates a color chooser pane with an initial color of white.
JColorChooser(Color initialColor): Creates a color chooser pane with the specified initial color.
JColorChooser(ColorSelectionModel model): Creates a color chooser pane with the specified ColorSelectionModel.
Commonly Used Methods: 
Creating a Custom Chooser Panel: The default color chooser provides five chooser panels: 
Swatches: For choosing a color from a collection of swatches.HSV: For choosing a color using the Hue-Saturation-Value color representation. Prior to JDK 7, It was known as HSB, for Hue-Saturation-Brightness.HSL: For choosing a color using the Hue-Saturation-Lightness color representation.RGB: For choosing a color using the Red-Green-Blue color model.CMYK: For choosing a color using the process color or four color model.
Swatches: For choosing a color from a collection of swatches.
HSV: For choosing a color using the Hue-Saturation-Value color representation. Prior to JDK 7, It was known as HSB, for Hue-Saturation-Brightness.
HSL: For choosing a color using the Hue-Saturation-Lightness color representation.
RGB: For choosing a color using the Red-Green-Blue color model.
CMYK: For choosing a color using the process color or four color model.
Below programs illustrate the use of JColorChooser class: 
1. Java program to implement JColorChooser class using ChangeListener: In this program, we first create a label at the top of the window where some text is shown in which we will apply color changes. Set the foreground and background color. Set the size and type of the font. Create a Panel and set its layout. Now set up the color chooser for setting text color. Using stateChanged() method, event is generated for change in color of the text by using getColor() method. Now create the GUI, create a setup window. Set the default close operation of the window. Create and set up the content Pane and add content to the frame and display the window.
Java
// Java program to implement JColorChooser// class using ChangeListenerimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.colorchooser.*; public class ColorChooserDemo extends JPanel     implements ChangeListener {     protected JColorChooser Jcc;    protected JLabel label;     public ColorChooserDemo()    {        super(new BorderLayout());         // Set up the Label at the top of the window        label = new JLabel("Welcome to GeeksforGeeks",                                       JLabel.CENTER);         // set the foreground color of the text        label.setForeground(Color.green);         // set background color of the field        label.setBackground(Color.WHITE);        label.setOpaque(true);         // set font type and size of the text        label.setFont(new Font("SansSerif", Font.BOLD, 30));         // set size of the label        label.setPreferredSize(new Dimension(100, 65));         // create a Panel and set its layout        JPanel bannerPanel = new JPanel(new BorderLayout());        bannerPanel.add(label, BorderLayout.CENTER);        bannerPanel.setBorder(BorderFactory.createTitledBorder("Label"));         // Set up color chooser for setting text color        Jcc = new JColorChooser(label.getForeground());        Jcc.getSelectionModel().addChangeListener(this);        Jcc.setBorder(BorderFactory.createTitledBorder(            "Choose Text Color"));         add(bannerPanel, BorderLayout.CENTER);        add(Jcc, BorderLayout.PAGE_END);    }     public void stateChanged(ChangeEvent e)    {        Color newColor = Jcc.getColor();        label.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("ColorChooserDemo");         // set default close operation of the window.        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         // Create and set up the content pane.        JComponent newContentPane = new ColorChooserDemo();         // content panes must be opaque        newContentPane.setOpaque(true);         // add content pane to the frame        frame.setContentPane(newContentPane);         // Display the window.        frame.pack();        frame.setVisible(true);    }     // Main Method    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();            }        });    }}
Output:
2. Java program to implement JColorChooser class using ActionListener: Create a button and a container and set the Layout of the container. Add ActionListener() to the button and add a button to the container. ActionListerner() has one method actionPerformed() which is implemented as soon as the button is clicked. Choose the color and set the background color of the container.
Java
// Java program to implement JColorChooser// class using ActionListenerimport java.awt.event.*;import java.awt.*;import javax.swing.*; public class ColorChooserExample extends      JFrame implements ActionListener {     // create a button    JButton b = new JButton("color");     Container c = getContentPane();     // Constructor    ColorChooserExample()    {         // set Layout        c.setLayout(new FlowLayout());         // add Listener        b.addActionListener(this);         // add button to the Container        c.add(b);    }     public void actionPerformed(ActionEvent e)    {         Color initialcolor = Color.RED;         // color chooser Dialog Box        Color color = JColorChooser.showDialog(this,                    "Select a color", initialcolor);         // set Background color of the Container        c.setBackground(color);    }     // Main Method    public static void main(String[] args)    {         ColorChooserExample ch = new ColorChooserExample();        ch.setSize(400, 400);        ch.setVisible(true);        ch.setDefaultCloseOperation(EXIT_ON_CLOSE);    }}
Output:
Note: The above programs might not run in an online IDE. Please use an offline compiler.Reference: https://docs.oracle.com/javase/7/docs/api/javax/swing/JColorChooser.html 
kalrap615
java-swing
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java