In this example, I am going to show you how to use apply different colors to swing components. Java JColorChooser is a class used to display the color pane to pick the colors in different formats.

Java JColorChooser :

JColorChooserDemo.java
package com.onlinetutorialspoint.swing;

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;
import javax.swing.JPanel;

public class JColorChooserDemo extends JFrame {

    private JButton button;
    private Color color;
    private JPanel colorPanel;
    
    public JColorChooserDemo(){
        super("JColorChooser Example");
        
        colorPanel = new JPanel();
        
        button = new JButton("Apply Color");
        
        button.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                color = JColorChooser.showDialog(JColorChooserDemo.this, "Pick Color", color);
                if(color == null)
                        color = Color.WHITE;
                colorPanel.setBackground(color);
            }
        });
        add(colorPanel,BorderLayout.CENTER);
        add(button,BorderLayout.SOUTH);
        setSize(400, 130);
        setVisible(true);
    }
    public static void main(String[] args) {
        JColorChooserDemo colorChooser = new JColorChooserDemo();
        colorChooser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

Output :

Java JColorChooser Example

Color Chooser :

Java JColorChooser Example 4

After Applying Color :

Java JColorChooser Example 5

RGB Color Picker :

Java JColorChooser Example 6

After Applying RGB Picker :

Java JColorChooser Example 7

Happy Learning 🙂

Leave A Comment