«Back to Home

Core Java

Topics

JColorChooser Class In Java

JColorChooser Class
 
In Java, JColorChooser class creates a color chooser dialog box. Thus, the user can select any color.
 
Constructors of JColorChooser class

JColorChooser()

This constructor is used to create a color chooser pane with White color initially.
 
JColorChooser(Color initialColor)

This constructor is used to create a color chooser pane with the particular color initially.
 
Methods of JColorChooser class

public static Color showDialog(Component c, String title, Color initialColor)

This method is used to show the color-chooser dialog box.
 
Let’s see an example of JColorChooser class, given below.
 
Code
  1. import java.awt.event.*;  
  2. import java.awt.*;  
  3. import javax.swing.*;  
  4. public class JColorChooserExample extends JFrame implements ActionListener {  
  5.     JButton jb;  
  6.     Container c;  
  7.     JColorChooserExample() {  
  8.         c = getContentPane();  
  9.         c.setLayout(new FlowLayout());  
  10.         jb = new JButton("Color");  
  11.         jb.addActionListener(this);  
  12.         c.add(jb);  
  13.     }  
  14.     public void actionPerformed(ActionEvent e) {  
  15.         Color initialcolor = Color.GREEN;  
  16.         Color col = JColorChooser.showDialog(this"Choose a color", initialcolor);  
  17.         c.setBackground(col);  
  18.     }  
  19.     public static void main(String[] args) {  
  20.         JColorChooserExample jch = new JColorChooserExample();  
  21.         jch.setSize(400400);  
  22.         jch.setVisible(true);  
  23.         jch.setDefaultCloseOperation(EXIT_ON_CLOSE);  
  24.     }  
  25. }  
42 
 
Output

43

44

45
 
Summary

Thus, we learnt that the JColorChooser class creates a color chooser dialog box. Thus, the user can select any color and we also learnt how to use it in Java.