O'Reilly logo

Java Swing by Dave Wood, Marc Loy, Robert Eckstein

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The Color Chooser

As the name indicates, the JColorChooser component is designed to allow users to pick a color. If your application supports customized environments (like the foreground, background, and highlight colors for text) this control might come in handy. You can pick colors from a palette and then look at that color in a preview panel that shows you how your color looks with black and white. The dialog also has an RGB mode that allows you to pick the exact amounts of red, blue, and green using sliders. The standard color chooser window looks like Figure 12.7.[26]

The default JColorChooser dialog in Swatches (top) and RGB (bottom) modes

Figure 12-7. The default JColorChooser dialog in Swatches (top) and RGB (bottom) modes

The JColorChooser class provides a static method for getting this popup going quickly. Here’s the code that produced the screen shots in Figure 12.7:

// ColorPicker.java
            
            
             // A quick test of the JColorChooser dialog. // import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ColorPicker extends JFrame { public ColorPicker() { super("JColorChooser Test Frame"); setSize(200, 100); final JButton go = new JButton("Show JColorChooser"); go.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Color c; c = JColorChooser.showDialog( ((Component)e.getSource()).getParent(), "Demo", Color.blue); go.setBackground(c); } }); getContentPane().add(go); addWindowListener(new BasicWindowMonitor()); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required