12.6 Developing a Custom Preview Panel


In addition to creating custom color chooser panels, you can create your own preview panel. You can use any JComponent just set the previewPanel property. As you update the color in the chooser, the foreground property of the preview panel changes. You can extend a container like JPanel and override the setForeground( ) method to gain more control over what parts of the pane are updated. Figure 12-9 shows a simple custom preview pane. We add two labels: one to show the foreground color (this label says, "This is a custom preview pane") and one to show the background color.

Figure 12-9. A custom preview panel added in a JColorChooser object
figs/swng2.1209.gif

Remember that some L&Fs don't allow you to set the foreground or background colors of some components. If you're on a Mac OS X system, for example, you can run ColorPicker3 this way:

% java -Dswing.defaultlaf=javax.swing.plaf.metal.MetalLookAndFeel ColorPicker3

This custom pane is added to our ColorPicker3 chooser by setting the previewPanel property after we create the chooser object:

chooser.setPreviewPanel(new CustomPane( ));

Here's the code for the CustomPane class. We build it as an inner class.

public class CustomPane extends JPanel {   JLabel j1 = new JLabel("This is a custom preview pane", JLabel.CENTER);   JLabel j2 = new JLabel("This label previews the background", JLabel.CENTER);   public CustomPane( ) {     super(new GridLayout(0,1));     j2.setOpaque(true);  // Otherwise, the background color won't show up     add(j1);     add(j2);   }   public void setForeground(Color c) {     super.setForeground(c);     if (j1 != null) {       j1.setForeground(c);       j2.setBackground(c);     }   } }


Java Swing
Graphic Java 2: Mastering the Jfc, By Geary, 3Rd Edition, Volume 2: Swing
ISBN: 0130796670
EAN: 2147483647
Year: 2001
Pages: 289
Authors: David Geary

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net