O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

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

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 ...

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