JColorChooser is a Swing component that provides a dialog box to allow users to select colors. It is a versatile and useful tool when developing graphical applications that require color customization, such as drawing programs, themes, or user interface color adjustments.
In this tutorial, we will learn how to use JColorChooser, display it in both a modal dialog and as a standalone panel, and interact with it programmatically.
Table of Contents
1. Creating a Basic JColorChooser
The simplest way to use a JColorChooser is by displaying it in a dialog box using the JColorChooser.showDialog() method. This displays a modal dialog that blocks the rest of the application until the user selects a color or cancels the dialog.
Example 1: Basic JColorChooser in a Dialog
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class JColorChooserExample1 { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("JColorChooser Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 300); JButton button = new JButton("Choose a Color"); JPanel panel = new JPanel(); panel.setBackground(Color.WHITE); // Default background color // Action listener to show the color chooser dialog button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Show the color chooser dialog Color selectedColor = JColorChooser.showDialog(frame, "Select a Color", panel.getBackground()); // If a color is selected (not canceled), change the panel's background if (selectedColor != null) { panel.setBackground(selectedColor); } } }); frame.setLayout(new BorderLayout()); frame.add(button, BorderLayout.NORTH); frame.add(panel, BorderLayout.CENTER); frame.setVisible(true); }); } }
Explanation:
The JColorChooser.showDialog() method displays a modal dialog box where the user can select a color.
The selected color is used to update the background color of the JPanel.
The dialog title is set to “Select a Color”, and the initial color displayed is the panel's current background.
2. Using JColorChooser as a Component
In addition to displaying JColorChooser in a dialog, it can also be used as a standalone component by adding it directly to a container, such as a JFrame or JPanel.
Example 2: Embedding JColorChooser in a GUI
import javax.swing.*; import java.awt.*; public class JColorChooserExample2 { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("Embedded JColorChooser"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500, 400); // Create a JColorChooser and add it to the frame JColorChooser colorChooser = new JColorChooser(); JPanel colorDisplayPanel = new JPanel(); colorDisplayPanel.setBackground(Color.WHITE); // Initial background color // Add a change listener to detect color changes in the color chooser colorChooser.getSelectionModel().addChangeListener(e -> { Color selectedColor = colorChooser.getColor(); colorDisplayPanel.setBackground(selectedColor); // Update panel background color }); frame.setLayout(new BorderLayout()); frame.add(colorChooser, BorderLayout.CENTER); frame.add(colorDisplayPanel, BorderLayout.SOUTH); frame.setVisible(true); }); } }
Explanation:
The JColorChooser component is embedded directly in the frame.
A change listener is attached to the color chooser's selection model to detect color changes in real-time and update the panel's background color.
This example demonstrates how to integrate a JColorChooser into your application layout as a permanent component rather than using it as a modal dialog.
3. Customizing the JColorChooser with Preview Panels
JColorChooser allows the use of custom preview panels where you can show a live preview of how the selected color will look when applied to specific components.
Example 3: Customizing the Preview Panel
import javax.swing.*; import java.awt.*; public class JColorChooserExample3 { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("Custom Preview JColorChooser"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500, 400); // Create a JColorChooser JColorChooser colorChooser = new JColorChooser(Color.RED); // Initial color is red // Create a custom preview panel JPanel previewPanel = new JPanel(); JLabel previewLabel = new JLabel("Preview Area"); previewLabel.setOpaque(true); // So we can see the background color change previewLabel.setPreferredSize(new Dimension(200, 100)); previewPanel.add(previewLabel); // Add a change listener to update the preview panel based on the selected color colorChooser.getSelectionModel().addChangeListener(e -> { Color selectedColor = colorChooser.getColor(); previewLabel.setBackground(selectedColor); // Update label background }); // Show the color chooser with the custom preview panel in a dialog int result = JOptionPane.showConfirmDialog( frame, colorChooser, "Select a Color", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null ); // If the user clicks OK, change the frame's background to the selected color if (result == JOptionPane.OK_OPTION) { frame.getContentPane().setBackground(colorChooser.getColor()); } frame.setVisible(true); }); } }
Explanation:
A JColorChooser is displayed in a custom dialog with a preview panel.
A JLabel is used as the preview area where the selected color is applied in real-time as the user interacts with the JColorChooser.
The frame's background is updated to the selected color if the user clicks “OK” in the dialog.
4. Using AbstractColorChooserPanel for Custom Panels
In more advanced use cases, you can create custom color chooser panels by extending AbstractColorChooserPanel. This allows you to create a specialized color chooser panel that fits your application needs.
Example 4: Creating a Custom Color Chooser Panel
import javax.swing.*; import javax.swing.colorchooser.AbstractColorChooserPanel; import java.awt.*; public class JColorChooserExample4 { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("Custom Color Panel Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500, 400); // Create a JColorChooser JColorChooser colorChooser = new JColorChooser(); // Add a custom color chooser panel colorChooser.addChooserPanel(new CustomColorChooserPanel()); frame.add(colorChooser, BorderLayout.CENTER); frame.setVisible(true); }); } // Custom color chooser panel static class CustomColorChooserPanel extends AbstractColorChooserPanel { @Override protected void buildChooser() { // Create a simple chooser panel with two buttons for "Red" and "Blue" JButton redButton = new JButton("Red"); redButton.addActionListener(e -> getColorSelectionModel().setSelectedColor(Color.RED)); JButton blueButton = new JButton("Blue"); blueButton.addActionListener(e -> getColorSelectionModel().setSelectedColor(Color.BLUE)); JPanel panel = new JPanel(); panel.add(redButton); panel.add(blueButton); add(panel); // Add the panel to the custom chooser } @Override public void updateChooser() { // No specific update needed for this simple panel } @Override public String getDisplayName() { return "Custom Colors"; } @Override public Icon getSmallDisplayIcon() { return null; } @Override public Icon getLargeDisplayIcon() { return null; } } }
Explanation:
A custom color chooser panel is created by extending AbstractColorChooserPanel.
In this example, the panel contains two buttons: “Red” and “Blue”. Clicking these buttons sets the selected color to either red or blue.
The custom panel is added to the JColorChooser, allowing the user to select predefined colors via the custom interface.
5. Handling the Color Selection Programmatically
Sometimes, you may want to handle the selected color programmatically without displaying a dialog. You can use the JColorChooser component directly to select colors and process them within your application logic.
Example 5: Handling Color Selection Without a Dialog
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class JColorChooserExample5 { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("JColorChooser Handling Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 300); JColorChooser colorChooser = new JColorChooser(); JPanel panel = new JPanel(); panel.setBackground(Color.WHITE); JButton applyButton = new JButton("Apply Selected Color"); // Apply the currently selected color from JColorChooser when the button is clicked applyButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Color selectedColor = colorChooser.getColor(); panel.setBackground(selectedColor); // Set panel background to selected color } }); frame.setLayout(new BorderLayout()); frame.add(colorChooser, BorderLayout.CENTER); frame.add(panel, BorderLayout.SOUTH); frame.add(applyButton, BorderLayout.NORTH); frame.setVisible(true); }); } }
Explanation:
This example shows how to select a color programmatically without displaying a modal dialog.
The JColorChooser is embedded in the frame, and the user can pick a color. When the “Apply Selected Color” button is clicked, the panel's background is updated to the selected color.
Conclusion
JColorChooser is a flexible and easy-to-use component in Java Swing for selecting colors. It can be used in various ways, including in modal dialogs, as embedded components, and with custom panels for more advanced scenarios.
Understanding how to utilize and customize JColorChooser will allow you to create rich, interactive user interfaces that incorporate color selection.
Summary of Key Points:
Basic Dialog: Use JColorChooser.showDialog() to display a modal dialog for color selection.
Embedded Component: You can add JColorChooser directly to a JFrame or JPanel for a more integrated interface.
Preview Panel: Customize the color chooser with preview panels that show real-time changes in color selection.
Custom Panels: Extend AbstractColorChooserPanel to create custom color selection panels.
Programmatic Color Selection: Handle color selection directly in your code using getColor() without showing a dialog.