DEV Community

Cover image for The Color Class
Paul Ngugi
Paul Ngugi

Posted on

The Color Class

The Color class can be used to create colors. JavaFX defines the abstract Paint class for painting a node. The javafx.scene.paint.Color is a concrete subclass of Paint, which is used to encapsulate colors, as shown in Figure below.

Image description

A color instance can be constructed using the following constructor:

public Color(double r, double g, double b, double opacity);

in which r, g, and b specify a color by its red, green, and blue components with values in the range from 0.0 (darkest shade) to 1.0 (lightest shade). The opacity value defines the transparency of a color within the range from 0.0 (completely transparent) to 1.0 (completely opaque). This is known as the RGBA model, where RGBA stands for red, green, blue, and alpha. The alpha value indicates the opacity. For example,

Color color = new Color(0.25, 0.14, 0.333, 0.51);

The Color class is immutable. Once a Color object is created, its properties cannot be changed. The brighter() method returns a new Color with a larger red, green, and blue values and the darker() method returns a new Color with a smaller red, green, and blue values. The opacity value is the same as in the original Color object.

You can also create a Color object using the static methods color(r, g, b), color(r, g, b, opacity), rgb(r, g, b), and rgb(r, g, b, opacity).

Alternatively, you can use one of the many standard colors such as BEIGE, BLACK, BLUE, BROWN, CYAN, DARKGRAY, GOLD, GRAY, GREEN, LIGHTGRAY, MAGENTA, NAVY, ORANGE, PINK, RED, SILVER, WHITE, and YELLOW defined as constants in the Color class. The following code, for instance, sets the fill color of a circle to red:

circle.setFill(Color.RED);

Top comments (0)