Home ยป Java Color Picker Tool Using Swing Tutorial

Java Color Picker Tool Using Swing Tutorial

In this tutorial, we will create a Color Picker Tool in Java using Swing.

The tool will allow users to select a color from a color palette, display the selected color, and show its RGB (Red, Green, Blue) values and Hexadecimal color code.

This is a fun and interactive way to explore colors and learn how they are represented in Java.

Features:

Allows users to pick a color using the JColorChooser component.
Displays the selected color in a panel.
Shows the RGB values and Hexadecimal color code of the selected color.
Provides a Copy to Clipboard feature for the hex color code.

Complete Code

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.datatransfer.StringSelection;

public class ColorPickerTool extends JFrame {

    private JPanel colorDisplayPanel; // Panel to show the selected color
    private JLabel rgbLabel;          // Label to display RGB values
    private JLabel hexLabel;          // Label to display Hex code
    private JButton pickColorButton, copyHexButton;

    // Constructor to set up the GUI
    public ColorPickerTool() {
        setTitle("Color Picker Tool");
        setSize(400, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);  // Center the window on the screen

        // Initialize components
        colorDisplayPanel = new JPanel();
        colorDisplayPanel.setBackground(Color.WHITE);  // Default color is white
        colorDisplayPanel.setPreferredSize(new Dimension(100, 100));

        rgbLabel = new JLabel("RGB: ");
        hexLabel = new JLabel("Hex: ");

        pickColorButton = new JButton("Pick a Color");
        copyHexButton = new JButton("Copy Hex Code");

        // Set up layout
        JPanel infoPanel = new JPanel(new GridLayout(2, 1));
        infoPanel.add(rgbLabel);
        infoPanel.add(hexLabel);

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(pickColorButton);
        buttonPanel.add(copyHexButton);

        setLayout(new BorderLayout());
        add(colorDisplayPanel, BorderLayout.WEST);
        add(infoPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        // Add action listeners
        pickColorButton.addActionListener(new PickColorButtonListener());
        copyHexButton.addActionListener(new CopyHexButtonListener());

        setVisible(true);
    }

    // Method to convert a Color object to Hex string
    private String getHexColor(Color color) {
        return String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue());
    }

    // Action listener for the Pick Color button
    private class PickColorButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Show color chooser dialog
            Color selectedColor = JColorChooser.showDialog(null, "Pick a Color", colorDisplayPanel.getBackground());

            // If a color is selected
            if (selectedColor != null) {
                // Update the color display panel
                colorDisplayPanel.setBackground(selectedColor);

                // Update RGB and Hex labels
                String rgbText = "RGB: " + selectedColor.getRed() + ", " + selectedColor.getGreen() + ", " + selectedColor.getBlue();
                rgbLabel.setText(rgbText);
                String hexText = "Hex: " + getHexColor(selectedColor);
                hexLabel.setText(hexText);
            }
        }
    }

    // Action listener for the Copy Hex button
    private class CopyHexButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Copy the hex value to clipboard
            String hexText = hexLabel.getText().replace("Hex: ", "").trim();
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(hexText), null);
            JOptionPane.showMessageDialog(null, "Hex code copied to clipboard!");
        }
    }

    // Main method to run the app
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new ColorPickerTool());
    }
}

Explanation of the Code

1. Import Statements

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.datatransfer.StringSelection;
javax.swing.*: Provides Swing components like JFrame, JButton, JPanel, and JLabel for creating the GUI.
java.awt.*: Provides layout and graphical utilities like Color, Dimension, BorderLayout.
java.awt.datatransfer.*: Provides clipboard functionalities for copying the hex color code to the clipboard.

2. Class Declaration and Instance Variables

public class ColorPickerTool extends JFrame {
    private JPanel colorDisplayPanel; // Panel to show the selected color
    private JLabel rgbLabel;          // Label to display RGB values
    private JLabel hexLabel;          // Label to display Hex code
    private JButton pickColorButton, copyHexButton;
}
JPanel colorDisplayPanel: A panel that will display the selected color.
JLabel rgbLabel, hexLabel: Labels to show the RGB values and Hexadecimal code of the selected color.
JButton pickColorButton, copyHexButton: Buttons for selecting a color and copying the hex code.

3. Constructor

public ColorPickerTool() {
    setTitle("Color Picker Tool");
    setSize(400, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);  // Center the window on the screen

    // Initialize components
    colorDisplayPanel = new JPanel();
    colorDisplayPanel.setBackground(Color.WHITE);  // Default color is white
    colorDisplayPanel.setPreferredSize(new Dimension(100, 100));

    rgbLabel = new JLabel("RGB: ");
    hexLabel = new JLabel("Hex: ");

    pickColorButton = new JButton("Pick a Color");
    copyHexButton = new JButton("Copy Hex Code");

    // Set up layout
    JPanel infoPanel = new JPanel(new GridLayout(2, 1));
    infoPanel.add(rgbLabel);
    infoPanel.add(hexLabel);

    JPanel buttonPanel = new JPanel();
    buttonPanel.add(pickColorButton);
    buttonPanel.add(copyHexButton);

    setLayout(new BorderLayout());
    add(colorDisplayPanel, BorderLayout.WEST);
    add(infoPanel, BorderLayout.CENTER);
    add(buttonPanel, BorderLayout.SOUTH);

    // Add action listeners
    pickColorButton.addActionListener(new PickColorButtonListener());
    copyHexButton.addActionListener(new CopyHexButtonListener());

    setVisible(true);
}

Frame Setup:

setTitle(“Color Picker Tool”): Sets the title of the window.
setSize(400, 200): Sets the window size.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Ensures that the app exits when the window is closed.
setLocationRelativeTo(null): Centers the window on the screen.

Component Initialization:

colorDisplayPanel: Displays the selected color with a default background color of white.
rgbLabel and hexLabel: Show the RGB values and Hexadecimal code of the selected color.
pickColorButton: A button to open the JColorChooser and allow the user to pick a color.
copyHexButton: A button to copy the hex code of the selected color to the clipboard.

Layout Setup:

infoPanel: A panel to hold the labels (rgbLabel, hexLabel) in a grid layout.
buttonPanel: A panel to hold the buttons (pickColorButton, copyHexButton).
setLayout(new BorderLayout()): Uses a border layout to position the components. The color display panel is placed on the left, the information panel in the center, and the buttons at the bottom.

4. getHexColor() Method

private String getHexColor(Color color) {
    return String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue());
}

This method converts a Color object to a Hexadecimal string (e.g., #FF5733).
String.format(): The %02x format ensures that the red, green, and blue values are converted to two-digit hexadecimal numbers.

5. Action Listener for the Pick Color Button

private class PickColorButtonListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        // Show color chooser dialog
        Color selectedColor = JColorChooser.showDialog(null, "Pick a Color", colorDisplayPanel.getBackground());

        // If a color is selected
        if (selectedColor != null) {
            // Update the color display panel
            colorDisplayPanel.setBackground(selectedColor);

            // Update RGB and Hex labels
            String rgbText = "RGB: " + selectedColor.getRed() + ", " + selectedColor.getGreen() + ", " + selectedColor.getBlue();
            rgbLabel.setText(rgbText);
            String hexText = "Hex: " + getHexColor(selectedColor);
            hexLabel.setText(hexText);
        }
    }
}
JColorChooser.showDialog(): Opens a color picker dialog that allows the user to select a color.
if (selectedColor != null): Ensures that the user has selected a valid color.

Update Components:

colorDisplayPanel.setBackground(selectedColor): Updates the background color of the panel to the selected color.
rgbLabel.setText(rgbText): Displays the RGB values of the selected color.
hexLabel.setText(hexText): Displays the hexadecimal code of the selected color.

6. Action Listener for the Copy Hex Button

private class CopyHexButtonListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        // Copy the hex value to clipboard
        String hexText = hexLabel.getText().replace("Hex: ", "").trim();
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(hexText), null);
        JOptionPane.showMessageDialog(null, "Hex code copied to clipboard!");
    }
}

Copy Hex to Clipboard:

Toolkit.getDefaultToolkit().getSystemClipboard().setContents(): Copies the hex code to the system clipboard.
JOptionPane.showMessageDialog(): Displays a confirmation dialog that the hex code has been copied.

7. Main Method

public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> new ColorPickerTool());
}
SwingUtilities.invokeLater(): Ensures that the GUI is created and updated on the Event Dispatch Thread (EDT), which is necessary for Swing applications.
new ColorPickerTool(): Creates and launches the color picker tool.

Customization Ideas

1. Allow Users to Copy RGB Values
Add a feature to copy the RGB values to the clipboard along with the hex code.

2. Add Color History

Add a panel to display the last few colors picked by the user, so they can revisit recently selected colors.

3. Improve the User Interface

Change the fonts, colors, and layout to make the tool more visually appealing.
Add tooltips to the buttons for better usability.

Conclusion

This Color Picker Tool in Java using Swing allows users to select colors from a palette, view their RGB and Hexadecimal values, and copy the hex code to the clipboard. It demonstrates:

Using JColorChooser to create a color picker dialog.
Displaying RGB and Hex values dynamically as the user selects a color.
Handling clipboard operations to allow the user to copy the hex code for later use.

Feel free to expand the functionality of this tool with additional features!

You may also like