How to use Java JColorChooser
The primary use of Java JColorChooser is to create a dialog box that allows the user to select different colors.This JColorChooser class inherits JComponent class.
How to declare Java JColorChooser class
[class JColorChooser extends JComponent implements Accessible
]
Java JColorChooser constructors
- JColorChooser()-creates a color panel with white as default.
- JColorChooser(Color color)-creates a color panel with the initial color specified.
Java JColorChooser Methods
- void addChooserPanel(AbstractColorChooserPanel panel)-adds color chooser panel to a color chooser.
- static Color showDialog(Component c,String t,Color color)-shows color chooser dialog.
Java JColorChooser Example
[
import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JColorChooser; import java.awt.Color; public class JavaJColorChooser extends JFrame { JavaJColorChooser() { super("Color chooser example"); Color color=Color.CYAN; JColorChooser.showDialog(this, "Java JColorChooser Example", color); setSize(300,300); setLayout(null); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String args[]) { new JavaJColorChooser(); } }
]
Java JColorChooser Example with ActionListener
[
import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JColorChooser; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.Color; import java.awt.Container; public class JavaJColorChooser extends JFrame { public JButton b; JavaJColorChooser() { super("Color chooser example"); b=new JButton("Color"); b.setBounds(10,10,100,30); add(b); //code to create JColorChooser Dialog Box
b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { Color initial=Color.BLUE; Color color=JColorChooser.showDialog(null, "Choose Color ", initial); b.setBackground(color); } }); setSize(300,300); setLayout(null); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String args[]) { new JavaJColorChooser(); } }
]
Lessons to Learn in this tutorial
JFrame class has several methods.These include.
- [ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);]-exits JFrame window on close button click.
- [ setSize(300,300);]
- [ setLocationRelativeTo(null);]-positions the window at the center of the screen.
Other Swing component used is this tutorial is JButton Class. Read more about adding ActionListener to JButton