Skip to content
Related Articles

Related Articles

Improve Article

Java Swing | JColorChooser Class

  • Last Updated : 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:

  1. A static convenience method that shows a modal color-chooser dialog and returns the color selected by the user.
  2. 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.
  3. 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:  

  1. JColorChooser(): Creates a color chooser pane with an initial color of white.
  2. JColorChooser(Color initialColor): Creates a color chooser pane with the specified initial color.
  3. JColorChooser(ColorSelectionModel model): Creates a color chooser pane with the specified ColorSelectionModel.

Commonly Used Methods: 

MethodDescription
setColor(Color color)Sets the current color of the color chooser to the specified color.
setColor(int c)Sets the current color of the color chooser to the specified color.
setColor(int r, int g, int b)Sets the current color of the color chooser to the specified RGB color.
showDialog(Component cmp, String title, Color init_Color)Shows a modal color-chooser dialog and blocks until the dialog is hidden.
updateUI()Notification from the UIManager that the L&F has changed 
 
setChooserPanels(AbstractColorChooserPanel[] panels)Specifies the Color Panels used to choose a color value.
addChooserPanel(AbstractColorChooserPanel panel)Adds a color chooser panel to the color chooser.
setUI(ColorChooserUI ui)Sets the L&F object that renders this component.
setSelectionModel(ColorSelectionModel newModel)Sets the model containing the selected color.
setPreviewPanel(JComponent preview)Sets the current preview panel.

Creating a Custom Chooser Panel: The default color chooser provides five chooser panels: 

  1. Swatches: For choosing a color from a collection of swatches.
  2. 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.
  3. HSL: For choosing a color using the Hue-Saturation-Lightness color representation.
  4. RGB: For choosing a color using the Red-Green-Blue color model.
  5. 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 ChangeListener
import 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 ActionListener
import 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
 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :