JColorChooser
Create color chooser dialog
With this tutorial we shall show you how to create a color chooser dialog in a Java Desktop Application. This is a very useful component when you have an application that let’s the user customize the application with colors and we want to make it easy for them to choose the color he wants.
In short, to create a color chooser dialog, one should follow these steps:
- Create a new
JFrame
. - Use
getContentPane().setLayout(new FlowLayout())
to set flow layout for the frame. - Create a new
JButton
that will fire up the file chooser. - Add a new
ActionListener
to the button. Override theactionPerformed
method. Now every time the user pressed the button, this method will fire up. Inside this method we are going to create the pop up dialog. - To create that dialog, create a new
JColorChooser
. - Use
showDialog
to pop up the color chooser dialog. The choice will return aColor
object.
Let’s see the code snippet that follows:
package com.javacodegeeks.snippets.desktop; import java.awt.Color; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JFrame; public class CreateColorChooserDialog { private static final long serialVersionUID = 1L; private static void createAndShowGUI() { // Create and set up the window. final JFrame frame = new JFrame("Centered"); // Display the window. frame.setSize(200, 200); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // set flow layout for the frame frame.getContentPane().setLayout(new FlowLayout()); JButton button = new JButton("Choose color"); button.setSize(50, 50); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Color color = JColorChooser.showDialog(frame, "Choose a color", Color.blue); System.out.println("The selected color was:" + color); } }); frame.getContentPane().add(button); } 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(); } }); } }
This was an example on how to create color chooser dialog in a Java Desktop Application.