Developing a Custom Chooser Panel

If you look at the JColorChooser component, you’ll realize that it is really just a tabbed pane with a color previewer below it. You can have as many chooser panels in it as you like. Let’s take a brief look at a panel that can be added to a color chooser. We’ll create a simple panel for selecting a shade of gray with one slider rather than pushing each slider for red, green, and blue to the same value. Figure 12-8 shows the resulting panel; its source code is presented here.

// GrayScalePanel.java // A simple implementation of the AbstractColorChooserPanel class. This class // provides a slider and a text field for picking out a shade of gray. // import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.colorchooser.*; public class GrayScalePanel extends AbstractColorChooserPanel implements ChangeListener, ActionListener { JSlider scale; JTextField percentField; // Set up our list of grays. We'll assume we have all 256 possible shades, // and we'll do it when the class is loaded. static Color[] grays = new Color[256]; static { for (int i=0; i<256; i++) { grays[i] = new Color(i, i, i); } } public GrayScalePanel( ) { setLayout(new GridLayout(0, 1)); // Create the slider and attach us as a listener. scale = new JSlider(JSlider.HORIZONTAL, 0, 255, 128); scale.addChangeListener(this); // Set up our display for the chooser. add(new JLabel("Pick your shade of gray:", JLabel.CENTER)); JPanel jp = new ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.