javaswingjcolorchooser

show only 2 panels in JColorChooser


I want to display only "Swartches" and "RGB" panel.

import java.awt.Color;
import java.awt.Dimension;
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;
import javax.swing.JOptionPane;
import javax.swing.colorchooser.AbstractColorChooserPanel;

public class ColorPickerSample {

    private static final long serialVersionUID = 1L;
    private static String hex = "#ff0033";

    private static void createAndShowGUI() {

        // Create and set up the window.
        final JFrame frame = new JFrame("Centered");

        // Display the window.
        frame.setSize(50, 100);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // set flow layout for the frame
        frame.getContentPane().setLayout(new FlowLayout());

        JButton button = new JButton("");
        System.out.println(Color.decode(hex));
        button.setBackground(Color.decode(hex));
        button.setPreferredSize(new Dimension(20, 20));

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                JColorChooser cc = new JColorChooser();
                AbstractColorChooserPanel defaultPanels[] = cc.getChooserPanels();
                cc.removeChooserPanel(defaultPanels[1]);
                cc.removeChooserPanel(defaultPanels[2]);
                cc.removeChooserPanel(defaultPanels[4]);
            //  frame.getContentPane().add(cc);
                //Color color = cc.showDialog(frame, "Choose a color", Color.blue);
                }
        });

        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(); 

            }

        });
    }

}

How can I show 2 panels only


Solution

  • The API also has a removeChooserPanel(...) method.

    So I guess you could do something like:

    AbstractColorChooserPanel defaultPanels[] = cc.getChooserPanels();
    cc.removeChooserPanel( defaultPanels[4] ); // CMYK
    cc.removeChooserPanel( defaultPanels[2] );  // HSL
    ...
    

    Edit:

    I am not sure how would I display this modified chooser in panel

    You will need to use the createDialog(...) method of the JColorChooser:

    JDialog dialog = JColorChooser.createDialog(
        frame.getContentPane(),
        "Choose a Color",
        true,
        cc,
        null,
        null);
    dialog.setVisible(true);
    System.out.println( cc.getColor() );