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.swing;

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

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

    public JColorChooserDemo() throws HeadlessException {
        initUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new JColorChooserDemo().setVisible(true));
    }

    private void initUI() {
        // Set title and default close operation of this JFrame.
        setTitle("JColorChooser Demo");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        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.
        colorChooser.getSelectionModel().addChangeListener(this);
        this.pack();
    }

    /**
     * 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);
    }
}

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

Here is an image of a JColorChooser component.

JColorChooser Component Demo

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.