32.6. Retrieving Metadata

 
[Page 992 ( continued )]

29.8. JColorChooser

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()  );   } } 

Figure 29.18. An instance of JColorChooser is displayed in an applet.


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) 


[Page 993]

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 .

Figure 29.19. An instance of JColorChooser is displayed in a dialog box with the OK, Cancel, and Reset buttons.


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.

Figure 29.20. The JColorChooser class contains a tabbed pane with three tabs for selecting colors using Swatches, HSB, and RGB.



[Page 994]

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 .


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

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