How to add color picker in Java Swing
In this tutorial, we are going to create a color picker using Java Swing. Java Swing is an integral component of the Java Foundation Classes(JFC). It is a library of graphical user interface components which is used to create window-based applications in Java.
Code
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; abstract public class ColorPicker extends JFrame implements ActionListener{ public static void main(String []args) { JFrame frame=new JFrame("Color Picker"); frame.setSize(300,400); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); final Container container=frame.getContentPane(); container.setLayout(new GridBagLayout()); JButton button=new JButton("Change Background Color"); container.add(button); button.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ Color color=JColorChooser.showDialog(null,"Select a Color",Color.black); container.setBackground(color); } }); frame.revalidate(); } }
Output
Explanation
In the above Java code, we are creating a simple color picker application using Swing.
First, we import the necessary classes from the javax.swing
and java.awt
packages.
Next, we define an abstract class named ColorPicker
which extends the JFrame class and implements the ActionListener
interface.
After that, we define the main method which is the entry point of the program. Inside the main method, we create a new JFrame object named “frame” with the title “Color Picker“.
Next, we set the size of the frame to 300×400 pixels using the setSize()
method, and used the setLocationRelativeTo(null)
method to locate it on the center of the screen.
We use the setDefaultCloseOperation()
method to exit the program when the frame is closed.
Finally, we set the frame to be visible using the setVisible(true)
method.
The next step is to get the content pane of the frame and set its layout to GridBagLayout.
Now, we create a JButton object named “button” with the label “Change Background Color” which is then added to the content pane.
Next, we add ActionListener to the button using an anonymous inner class. When the button is clicked, the actionPerformed()
method of the ActionListener is called.
Inside this method, a JColorChooser
dialog is displayed to allow the user to select a color.
The selected color is then set as the background color of the container (content pane).
Finally, the frame is revalidated to ensure that any changes to the layout are applied.
Thank you for learning from CodeSpeedy. If you have any doubts or questions then feel free to ask them in the comments section below.
You can also read:
Leave a Reply