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
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 ColorPicker3This 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 ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access