Color Chooser

Swing is chock full of goodies. JColorChooser is yet another ready-made dialog supplied with Swing; it allows your users to choose colors. The following brief example shows how easy it is to use JColorChooser:

 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;
 public class LocalColor {
 public static void main(String[] args) {
 final JFrame frame = new JFrame("LocalColor v1.0");
 final Container content = frame.getContentPane( ); // unnecessary in 5.0+
 content.setLayout(new GridBagLayout( ));
 JButton button = new JButton("Change color...");
 content.add(button);
 button.addActionListener(new ActionListener( ) {
 public void actionPerformed(ActionEvent e) {
 Color c = JColorChooser.showDialog(frame,
 "Choose a color", content.getBackground( ));
 if (c != null) content.setBackground(c);
 }
 });
 frame.setSize(200, 200);
 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
 frame.setVisible(true);
 }
 }


This example shows a frame window with a single button. When you click on the button, a color chooser pops up. After you select a color, it becomes the background color of the frame window. Basically, all we have to do is call JColorChooser's static method showDialog( ). In this example, we specified a parent component, a dialog title, and an initial color value. But you can get away with just specifying a parent component. Whatever color the user chooses is returned; if the user presses the Cancel button, null is returned.

Java ScreenShot
Comments