Search code examples
javaswinguser-interfacejcolorchooser

Java Swing How can I create a Color Swatch in my custom ColorChooserPanel?


I'm working on my custom ColorChooserPanel class, but I don't know how to create a ColorSwatch.

I found a class named ColorSwatch or something like that but its package private and I can't access it.

How can I ensure that I have a proper color chooser?


Solution

  • First, you need to think about the way this should work, to formulate your goals into action points that you can always check and see whether and how they are fulfilled:

    • it should be displayed
    • it should handle click events
    • it should be able to return a color (the last chosen color, or a default in lack of that)

    Now, a very common way of supporting color choosers is to have something like in this image:

    enter image description here

    However, this is way too complex for a first implementation. You should first have something which "works", that is, you are able to choose colors to taste success and then work out the subsequent details. Unless you say otherwise, I'm assuming that the Basic colors section is good for now. In that case, you can create a class, which contains a JPanel, containing clickable elements. Your class needs to have a Color member, which one can get calling a getter and which is set when a clickable item inside your JPanel is clicked. The clickable items can be JPanels on their own, for example.

    If you prefer something ready-made, then kindly read these:

    https://docs.oracle.com/javase/tutorial/uiswing/components/colorchooser.html

    https://coderanch.com/t/332515/java/Color-Palette