Java Swing Tutorial - Java Swing Colors








An object of the java.awt.Color class represents a color. The Color class is immutable and it does not have any method that will let we set the color component values after we create a Color object.

We can create a Color object using its RGB (Red, Green, and Blue) components.

RGB values can be specified as float or int values. As a float value, each component in RGB ranges from 0.0 to 1.0. As an int value, each component in RGB ranges from 0 to 255.

The alpha value of a color defines the transparency of the color. As a float, its value ranges from 0.0 to 1.0, and as an int, its value ranges from 0 to 255.

The value of 0.0 or 0 for alpha indicates that a color is fully transparent, whereas the value of 1.0 or 255 indicates that it is fully opaque.

We can create a Color object as follows.

To create red color

Color  red  = new Color(255, 0, 0);

To create green color

Color  green   = new Color(0, 255,  0);

To create blue color

Color  blue   = new Color(0, 0, 255);

To create white color

Color  white   = new Color(255, 255,  255);

To create black color

Color  black = new Color(0, 0, 0);

The alpha component is default to 1.0 or 255.

The following code creates a red transparent color by specifying the alpha component as 0:

transparentRed = new Color(255, 0, 0, 0);

The Color class defines many color constants. We can use Color.red or Color.RED constant.

We can obtain its red, green, blue, and alpha components using its getRed(), getGreen(), getBlue(), and getAlpha() methods, respectively.

We can create a color using HSB (Hue, Saturation, and Brightness) components. The Color class has two methods called RGBtoHSB() and HSBtoRGB() that let we convert from the RBG model to the HSB model and vice versa.

A Color object is used with the setBackground(Color c) and setForeground(Color c) methods of the Swing components.

The background color is the color with which a component is painted, whereas the foreground color is usually the color of the text displayed in the component.

If a component is transparent, it does not paint pixels in its bounds. Rather, it lets the container's pixels show through. In order to see the background color, we must make the component opaque by calling its setOpaque(true) method.

The following code creates a JLabel and sets its background color to red and foreground (or text) color to black:

JLabel testLabel  = new JLabel("Color Test");
testLabel.setOpaque(true);
testLabel.setBackground(Color.RED);
testLabel.setForeground(Color.BLACK);