How do I use JColorChooser component?

The JColorChooser is a Swing component that provides a palette from where we can select a color code in RGB format. The JColorChooser component has two parts, the tabbed pane of color selection and a preview box. The tabbed has three tabs which allows us to select a color from a swatches, a HSB (Hue, Saturation and Brightness) combination and an RGB (Red Blue Green) color combination.

package org.kodejava.example.swing;

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

public class ColorChooserDemo extends JFrame implements ChangeListener {
    private JColorChooser colorChooser = null;

    public ColorChooserDemo() throws HeadlessException {

    private void initUI() {
        // Set title and default close operation of this JFrame.
        setTitle("JColorChooser Demo");
        setLayout(new BorderLayout());

        // Creates an instance of JColorChooser component and
        // adds it to the frame's content.
        colorChooser = new JColorChooser();
        getContentPane().add(colorChooser, BorderLayout.PAGE_END);

        // Add a change listener to get the selected color in this
        // JColorChooser component.

     * Handles color selection in the JColorChooser component.
     * @param e the ChangeEvent
    public void stateChanged(ChangeEvent e) {
        // Get the selected color in the JColorChooser component
        // and print the color in RGB format to the console.
        Color color = colorChooser.getColor();
        System.out.println("color = " + color);

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ColorChooserDemo().setVisible(true);

When you run the program above a frame with JColorChooser component will be shown. If you click a color from the color selection a string of the color in an RGB format will be printed in the console.

Here is an image of a JColorChooser component.

JColorChooser Demo

Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply