Java Reference
In-Depth Information
To compare two Color objects you use the equals() method. For example, to compare two color objects
colorA and colorB , you could write the following:
if(colorA.equals(colorB)) {
// Do something...
}
The equals() method returns true if all three components of the two Color objects are equal. As with
object references in general, don't use the == operator to compare Color objects. If you do, you are just
determining whether the two Color object references refer to the same object. Applying the == operator to
two different Color objects that represent the same color results in false .
You could also use the getRGB() method for a Color object when you are comparing colors:
if(colorA.getRGB() == colorB.getRGB()) {
// Do something....
}
This compares the two integer RGB values for equality, so here the == operator produces the correct res-
ult.
NOTE Note that the Color class also supports color transparency by storing an alpha com-
positing value in the range 0 to 255, where 0 is completely transparent and 255 is completely
opaque. You also have Color constructors that accept color component values between 0.0
and 1.0.
System Colors
The java.awt package defines the class SystemColor as a subclass of the Color class. The SystemColor
class encapsulates the standard colors that the native operating system uses for displaying various compon-
ents. The class contains definitions for 26 public final static variables of type SystemColor that specify
the standard system colors used by the operating system for a range of GUI components. For example, the
system colors for a window are referenced by the following:
window Defines the background color for a window
windowText Defines the text color for a window
windowBorder Defines the border color for a window
You can find the others covering colors used for menus, captions, controls, and so on, if you need them,
by looking at the documentation for the SystemColor class.
If you want to compare a SystemColor value with a Color object, then you must use the getRGB() meth-
od in the comparison. This is because the SystemColor class stores the colors internally in a way that uses
the fields it inherits from the Color class differently from a normal Color object. For example, to see wheth-
er colorA corresponds to the system background color for a window, you could write:
if(colorA.getRGB() == SystemColor.window.getRGB()) {
// colorA is the window background color...
Search WWH ::




Custom Search