Java Reference
In-Depth Information
PITFALL: (continued)
(You may feel that the values of 127 should be replaced by 128 , but that is a minor
point. You are not likely to even notice the difference in color between, say, 127 red
and 128 red.)
In any final code produced, these float numbers should normally be replaced by
defined constants, such as
public static final float RED_VALUE = ( float )0.5;
public static final float GREEN_VALUE = ( float )0.0;
public static final float BLUE_VALUE = ( float )0.5;
Note that even though the defined constants are specified to be of type float , you
still need a type cast.
The JColorChooser Dialog Window
The class JColorChooser can be used to produce a dialog window that allows you to
choose a color by looking at color samples or by choosing RGB values. The static
method showDialog in the class JColorChooser produces a window that allows the
user to choose a color. A sample program using this method is given in Display 18.20.
The statement that launches the JColorChooser dialog window is the following:
sampleColor =
JColorChooser.showDialog( this , "JColorChooser", sampleColor);
When this statement is executed, the window shown in the second GUI picture in Dis-
play 18.20 is displayed for the user to choose a color. Once the user has chosen a color
and clicked the OK button, the window goes away and the chosen color is returned as the
value of the JColorChooser.showDialog method invocation. So, in this example,
the Color object returned is assigned to the variable sampleColor . If the user clicks the
Cancel button, then the method invocation returns null rather than a color.
The method JColorChooser.showDialog takes three arguments. The first argu-
ment is the parent component, which is the component from which it was launched.
In most simple cases, it is likely to be this , as it is in our example. The second argu-
ment is a title for the color chooser window. The third argument is the initial color for
the color chooser window. The window shows the user samples of what the color he or
she chooses will look like. The user can choose colors repeatedly, and each will be dis-
played in turn until the user clicks the OK button. The color displayed when the color
chooser window first appears is that third argument.
The color chooser window has three tabs at the top labeled Swatches , HSB , and RGB .
This gives the user three different ways to choose colors. If the Swatches tab is clicked,
the window displays color samples for the user to choose from. This is the way the
Search WWH ::




Custom Search