Color Class
- Defined in java.awt.* library.
- Specifies a color in RGBA (red, green, blue, alpha) format.
the RGB part refers to the intensity of the red, green, and blue
light. 0 values is no light, a value of 255 is maximum intensity.
If RGB are
all 0, black results, if all 255, then white results. The alpha portion
is
used to specify opaqueness/transparency.
- Static colors - the color class provides a good number of static
constants for common colors. they can be reference directly. E.g.
- Color.red - bright red
- Color.green - bright green.
- others Color.black, Color.red, Color.magenta, Color.cyan, etc.
- Colors can also be created by creating an instance of the Color
class. Here are two of the more useful constructors
public Color(int r, int g, int b) - Creates an
opaque sRGB color with the specified red, green, and blue values in the
range (0 - 255). The actual color used in rendering depends on finding
the best match given the color space available for a given output
device. Alpha is defaulted to 255.
public Color(int r, int g, int b, int a) -
Creates an sRGB color with the specified red, green, blue, and alpha
values in the range (0 - 255). For the RGB the lower the value,
the darker the color, for Alpha, the lower the value the more
translucent the color.
examples:
Color c1 = new Color(128,0,0); // dark red opaque
Color c2 = new Color(0,255,0,128); // bright green, somewhat
translucent
JColorChooser
- JColorChooser provides a pane of controls designed to allow a
user to manipulate and select a color.
- JColorChooser can be invoked in several ways
- use a static method (does not require creating an instance of
the class) to pop up a color chooser dialog
- as a panel within an application.
- if you use it as a panel within an application, then use the
getColor method to select the current color.
- static method:
public static Color showDialog(Component
component, String
title, Color initialColor)
Shows a modal color-chooser dialog and blocks until the
dialog is hidden. If the user presses the "OK" button, then this method
hides/disposes the dialog and returns the selected color. If the user
presses the "Cancel" button or closes the dialog without pressing "OK",
then this method hides/disposes the dialog and returns null.
Parameters:
component - the parent Component for the dialog
title - the String containing the dialog's title
initialColor - the initial Color set when the color-chooser is shown
Returns:
the selected color or null if the user opted out
Example:
Color myColor = JColorChooser.showDialog(this,
"Select a color",Color.red);