JColorChooser in Swing - A Simplified Example

JColorChooser is a dialog that allows user to select a wide range of colors. Not in the AWT, JColorChooser simplifies color choosing. To program, we just need one static method that takes no more than three parameters corresponding to parent, title of the dialog and initial color. The method returns the color selected by the user. The program is simplified to the maximum extent possible and its motive is to set the user selected color as background for the JFrame. Before we look into the example, let us look at the prototype of the method.

public static Color showDialog(Component parent,String title,Color initialColor)
This method shows JColorChooser and returns the selected color when the user presses OK. If the user presses Cancel or closes the dialog, then null is returned.

import javax.swing.*;
import java.awt.*;
class JColorChooserExample extends JFrame
    public JColorChooserExample()
    private void createAndShowGUI()
        setTitle("JColorChooser Example");
        setLayout(new FlowLayout());
        // c is the selected color
        // this represents current jframe
        // next is title
        // inital color
        Color c=JColorChooser.showDialog(this,"Choose a background",Color.RED);
        // Background is set when user presses OK
    public static void main(String args[])
        new JColorChooserExample();

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it.

Screenshot of JColorChooser Example

Posted by at on

Tags: Swing Components,