I'm making a program that draws some shapes and fills them with color. I need to change the 'line' color, and want the user to be able to select the color.
How can I, when clicking a button "Choose Color", have a set of colours appear below the button? Is it possible for the selector to be embedded in the UI below the button (and not pop up in a window)?
I want to display a color selector like in Paint.
Here is a colour selection button class:
Use it in this way:
You can use the
JColorChooser
like this:java.awt.Component
instance. Could also benull
.The dialog returns the selected color if the user presses
ok
ornull
if he clicked oncancel
.See this page for more information: http://docs.oracle.com/javase/tutorial/uiswing/components/colorchooser.html.
Edit: include ColorChooser into existing contentpane
The above code shows how to create a pop up with for the
JColorChooser
, but it is also possible to "include" it into the existing contentpane.This is the code to initialize both components (
JButton
andJColorChooser
):The button will be added immediately, but the color chooser not yet. It will be added in the
toggleColorChooser
method:The color chooser will be added to the panel beneath the button. You may change the bounds if you have a different layout or if you're using a layout manager.
As you can see, you'll need a variable called
toggled
. Just add it as class variable:The last method will be called it the user selects a color on the color chooser. It will change the background color of the button:
I improved a Java Swing Color Picker component that looks beautiful and allows enhanced color manipulation:
Simply add the Maven dependency
to your project. Now you can add the ColorPickerPanel to your user interface.