You created a color dialog in the preceding example as a subclass of JDialog , which is a subclass of java.awt.Dialog (a top-level heavy-weight component). Therefore, it cannot be added to a container as a component. Color dialogs are commonly used in GUI programming. Swing provides a convenient and versatile color dialog named javax.swing.JColorChooser . JColorChooser is a lightweight component inherited from JComponent . It can be added to any container. For example, the following code places a JColorChooser in an applet, as shown in Figure 29.18:
public class JColorChooserDemo extends javax.swing.JApplet { public JColorChooserDemo() { this .add( new javax.swing.JColorChooser() ); } }
Often an instance of JColorChooser is displayed in a dialog box using JColorChooser 's static showDialog method:
public static Color showDialog(Component parentComponent, String title, Color initialColor)
For example, the following code creates a JColorChooser in an applet, as shown in Figure 29.18:
import javax.swing.*; import java.awt.Color; public class JColorChooserDemo extends javax.swing.JApplet { public void init() { Color color = JColorChooser.showDialog( this , "Choose a color" , Color.YELLOW); } }
The showDialog method creates an instance of JDialog with three buttons , OK, Cancel, and Reset, to hold a JColorChooser object, as shown in Figure 29.19. The method displays a modal dialog. If the user clicks the OK button, the method dismisses the dialog and returns the selected color. If the user clicks the Cancel button or closes the dialog, the method dismisses the dialog and returns null .
JColorChooser consists of a tabbed pane and a color preview panel. The tabbed pane has three tabs for choosing colors using Swatches, HSB, and RGB, as shown in Figure 29.20. The preview panel shows the effect of the selected color.
Note
JColorChooser is very flexible. It allows you to replace the tabbed pane or the color preview panel with custom components. The default tabbed pane and the color preview panel are sufficient. You rarely need to use custom components . |