CodeGym /Java Blog /Java Classes /Java.Awt.Color Class
Author
Pavlo Plynko
Java Developer at CodeGym

Java.Awt.Color Class

Published in the Java Classes group
If you are mastering Java Abstract Toolkit, you will have to learn the applications of Java AWT Color Class. Since there are a lot of constructors and methods involved, it might feel intimidating at first. But no worries, we got you covered:) With this full rundown on Java AWT Color, you’ll learn how to create a new color type and manage it in no time. We’ll also offer a couple of practice tests that’ll help you hone your skill.

What Is AWT Color Class in Java?

The primary purpose of AWT Color is to allow developers to create new colors using Java code using RGB (red, green, blue), RGBA (red, green, blue, alpha), or HSB (hue, saturation, BRI components) packages. The class contains two values - the code of the shade and the value of opacity/transparency. Java.Awt.Color Class - 1Here’s how you declare Class java.awt.Color:

public class Color
   extends Object
      implements Paint, Serializable
To declare different types of colors using Class.java.awt.Color, developers use constructors - we will take a look at them now.

AWT.Color Constructors in Java

Depending on the parameter of the color you want to create, you’ll need to use a specific type of color constructor. There is a handful of these - let’s examine them one by one.
  • Color(float r, float g, float b) is the class you use to define a color in the RGB color scheme that is opaque. You can specify the color range anywhere between 0.0 and 0.1.
  • Color(float r, float b, float g, float a) is the class that defines an RGBA color (the range of available values is 0.0 and 0.1).
  • Color(ColorSpace c, float[], co, float a) defines a color in the ColorSpace you specify beforehand. A developer specifies the range of color components in the float array of a defined alpha.
  • Color(int, rgb) is a class creating an RGB color (opaque). Make sure to pay attention to the component value of the constructor - 16-23 for red, 8-15 for green, 0-7 for blue.
  • Color(int r, int g, int b) - a method used to define an opaque RGB color. The value of the color should lie between 0 and 255.
  • Color(int r, int g, int b, int a) - creates a color in the RGBA scheme (0-255).
  • Color(int rgba, boolean b) is used to create sRGB colors within a defined combined value. The range of values spans 24-31 for alpha, 16-23 for red, 8-15 for green, and 0-7 for blue.
Other than that, class.awt.color operates with the fields, inherited from Java.awt.Transparency:
  • TRANSLUCENT represents whether or not the color contains alpha values and has two values - 0 and 1.
  • OPAQUE assigns the alpha value of 1 to the object guaranteeing it complete opaqueness.
  • BITMASK represents the absolute opaqueness or transparency value and lies within the range of (0;1) where 0 is full transparency and 1 is extreme opaqueness.

Top 15 Methods to Use With Java AWT Color Class

To manipulate a color, adjust its darkness or brightness, Java developers rely on different methods. There are dozens of those so you don’t have to learn all of them by heart. However, when it comes to the most widely used Java AWT Color methods, we narrowed the list down to fifteen. Remembering these without having to reference the Java API documentation would be helpful to developers.

darker()

The method is used to create a new color that is a darker version of the color you’ve already defined. Example:

Color.green.darker()
If applying darker() once isn’t enough to create a shade you need, feel free to reapply the method as many times as you want to, as shown below:

Color.green.darker().darker().darker().darker().darker()

brighter()

As the name suggests, Color brighter() is used to brighten up the shade you already have. Similarly to darker(), it could be used multiple times per single color. Example:

Color myColor = Color.RED;          

    JLabel label = new JLabel("First Name");
    label.setForeground(myColor.brighter());

int getAlpha()

If you want to return the alpha component of your color, use this method. Keep in mind that alpha values lie within the 0-255 range. Here’s the example of the method’s application and return. Example:

alpha = Color.black.getAlpha();
return new Color(components[0], components[1], components[2], alpha);

static Color getColor(String nm)

Java developers can use this method to locate a color using system properties. There are other methods handling similar objectives:
  • static Color getColor(String nm, int v)
  • static Color getColor(String nm, Color v)

static Color decode (string nm)

This method is used display a color as a string. After the conversion is complete, a developer will get a defined opaque color. Example:

public static Color decodeColor(String hexColor) {

 return Color.decode(hexColor);

PaintContext createContext(ColorModel cm, Rectangle r, Rectangle2D r2d, AffineTransform xform, RenderingHints hints)

This method looks complex but it’s easier to manipulate than it seems. Paint Context CreateContext() is used to define a repeated solid color pattern. Example:

 public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds,

                  AffineTransform xform, RenderingHints hints)

 {
   try
   {
     return new AxialShadingContext(shading, cm, xform, matrix, deviceBounds);
   }
   catch (IOException e)

   {

     LOG.error("An error occurred while painting", e);

     return new Color(0, 0, 0, 0).createContext(cm, deviceBounds, userBounds, xform, hints);

   }
 }
}

float[] getComponents(ColorSpace cspace, float[] compArray)

This is a Java method you can apply to a color to return its float array and alpha components. The method applies to a given ColorSpace defined by cspace. Example:

public float[] getComponents(ColorSpace cspace, float[] compArray) {

return myColor.getComponents(cspace, compArray);

}

ColorSpace getColorSpace()

Java developers can use this method to return the color space for a chosen color. Another way to get a color space for a given entry is by applying Arrays.to.String. This is a more complex strategy, as seen in the example below: Examples:

public class Main {
  public static void main(String[] args) {

    Color myColor = Color.RED;          

    System.out.println(Arrays.toString(myColor.getComponents(ColorSpace.getInstance(ColorSpace.CS_CIEXYZ),null)));

getHSBColor(float h, float s, float b)

Java developers apply this method to create a new color object based on the values of the HSB model. Example:

 private Color colorAt(int y)

 {
   return Color.getHSBColor(1 - (float) y / (height - 1), 1, 1);
 }
}

getGreen()	returns the green component in the range 0-255 in the default sRGB space.

getGreen()

This Java method returns the value of the green component for the color you created. All the values fit within the range that corresponds to green in the RGB color scheme. Example:

Color clickBoxColor = new Color(color.getRed(), color.getGreen(), color.getBlue(), 20);

getRed()

Similarly to getGreen(), getRed returns the value for the red component of a given color. You’ve already seen how the method was applied in the example above.

getBlue()

This method returns the value of blue within the range of values of the RGB color scheme. Likewise, for the example of using getBlue(), see the description of getGreen().

getAlpha()

The getAlpha() method is used in Java when a developer wants to find the alpha value of a given color. Similarly to RBG, the alphas of all colors lie within the 0-255 range. Example: here’s how getAlpha() was used as a part of a loop.

int alpha = color.getAlpha();
	if (alpha != 255)
	{
		setStrokeAlpha(alpha);
		strokeAlphaSet = true;

getTransparency()

This method returns the transparency value you or another developer have specified for the color when creating it. Example:

public int getTransparency() {

return myColor.getTransparency();

boolean equals(Object obj)

This method is highly useful if you are comparing two colors to each other. It lets Java developers know whether two color objects have equal values. Example:

import java.awt.Color;
public class Main {
  public static void main(String[] a) {
    Color myBlack = new Color(0, 0, 0); // Color black
    Color myWhite = new Color(255, 255, 255); // Color white
    System.out.println(myBlack.equals(myWhite));
  }
}

equals(Object obj)

Similarly to boolean equals(Object obj), this one is a comparative method. We use it to determine whether color objects are equal to each other. Example:

Object a = new Object(); Object b = new Object(); return(a.equals(b));

Guide to Main Colors Used in Java

Now that you have an understanding of the methods used to manipulate colors in Java, let’s take a look at the field types you will be working with. These are the actual static colors Java developers can define. You can either define a color by entering its name (make sure you enter it exactly the way it’s written in official documentation) or specifying its RGB value. Let’s take a look at the palette developers use:
Field name Description
static color black (BLACK) Defines the black color
static color white (WHITE) Defines the white color
static color blue (BLUE) Used to define blue
static color gray (GRAY) Defines the gray color
static color darkgray (DARK_GRAY) Defines a darker shade of gray
static color lightGray (LIGHT_GRAY) Defines a lighter shade of gray
static color green (GREEN) Used to define the green color
static Color magenta (MAGENTA) Defines the magenta shade
static Color pink (PINK) Defines pink in Java
static Color orange (ORANGE) Creates the orange color in Java
static Color yellow (YELLOW) Used to define yellow
static Color red (RED) Defines red color in Java

Practice Problems For Using AWT.Color in Java

Do you feel like you have a solid foundation of AWT Color in Java? Let’s test these skills by solving a few practical problems - here, you’ll have to apply constructors and common methods, as well as other non-color-related Java tools. Practice problem #1. Create a custom component that lets a program user tweak RGB levels in a color (similar to RGBColorChooser). Make sure to include getColor() into your components. Make the component a Panel subclass, not an applet. Answer: this is a fairly complex problem - let’s break it down into manageable steps:
  1. Convert an RGBChooser into a component.
  2. Add a new routine to the component - getColor().
  3. Add setColor() to set the color.
Here’s the sample code you should get at the end of the day:

import java.awt.*;
    import java.awt.event.*;
    
    public class RGBChooserComponent extends Panel implements AdjustmentListener {
       
       private Scrollbar redScroll, greenScroll, blueScroll;   // Scroll bars.
       
       private Label redLabel, greenLabel, blueLabel;  // For displaying RGB values.
                     
                     
       private Canvas colorCanvas;  // Color patch for displaying the color.
                     
       public RGBChooserComponent() {  // Constructor.
       
           /*Now let’s add scrollbars with values from 0 to 255. */
           
           redScroll = new Scrollbar(Scrollbar.HORIZONTAL, 0, 10, 0, 265);
           greenScroll = new Scrollbar(Scrollbar.HORIZONTAL, 0, 10, 0, 265);
           blueScroll = new Scrollbar(Scrollbar.HORIZONTAL, 0, 10, 0, 265);
           
           /* Create Labels showing current RGB and HSB values. */
           
           redLabel = new Label(" R = 0");
           greenLabel = new Label(" G = 0");
           blueLabel = new Label(" B = 0");
           
           /* We are setting backgrounds for Scrollbars and Labels, so they get the default
              gray background of the applet. */
           
           redScroll.setBackground(Color.lightGray);
           greenScroll.setBackground(Color.lightGray);
           blueScroll.setBackground(Color.lightGray);
           
           redLabel.setBackground(Color.white);
           greenLabel.setBackground(Color.white);
           blueLabel.setBackground(Color.white);
           
           /* Establish a panel that would listen for changes to the Scrollbars' values */
           
           redScroll.addAdjustmentListener(this);
           greenScroll.addAdjustmentListener(this);
           blueScroll.addAdjustmentListener(this);
           
           /* Add a canva, the background color of which will always match the currently selected color. */
           
           colorCanvas = new Canvas();
           colorCanvas.setBackground(Color.black);
           
           /* Create the applet layout, which consists of a row of
              three equal-sized regions holding the Scrollbars,
              the Labels, and the color patch.  The background color
              of the applet is gray, which will show around the edges
              and between components. */
           
           setLayout(new GridLayout(1,3,3,3));
           setBackground(Color.gray);
           Panel scrolls = new Panel();
           Panel labels = new Panel();
           
           add(scrolls);
           add(labels);
           add(colorCanvas);
           
           /* Add the Scrollbars and the Labels to their respective panels. */
           
           scrolls.setLayout(new GridLayout(3,1,2,2));
           scrolls.add(redScroll);
           scrolls.add(greenScroll);
           scrolls.add(blueScroll);
           
           labels.setLayout(new GridLayout(3,1,2,2));
           labels.add(redLabel);
           labels.add(greenLabel);
           labels.add(blueLabel);
           
       } // end init();
       
       
       public Color getColor() {
              // Get the color currently displayed by the component.
           int r = redScroll.getValue();
           int g = greenScroll.getValue();
           int b = blueScroll.getValue();
           return new Color(r, g, b);
       }
       
       
       public void setColor(Color c) {
             // Set the component to display the given color.
             // (Ignore this if c is null.)
          if (c != null) {
             int r = c.getRed();      // Get the color levels from the color.
             int g = c.getGreen();
             int b = c.getBlue();
             redLabel.setText(" R = " + r);   // Set the labels.
             greenLabel.setText(" G = " + g);
             blueLabel.setText(" B = " + b);
             redScroll.setValue(r);        // Set the scrollbars.
             greenScroll.setValue(g);
             blueScroll.setValue(b);
             colorCanvas.setBackground(new Color(r,g,b));  // Set the canvas.
             colorCanvas.repaint();
          }
       }
       
       
       public Dimension getMinimumSize() {
              // Specify the minimum reasonable size of this component.
          return new Dimension(150,40);
       }
       
       
       public Dimension getPreferredSize() {
              // Specify the preferred size of this component.
          return new Dimension(280,80);
       }
       
    
       public void adjustmentValueChanged(AdjustmentEvent evt) {
               // This is called when the user has changed the values on
               // one of the scrollbars.  All the scrollbars are checked,
               // the labels are set to display the correct values,
               // and the color patch is reset to correspond to the new color.
           int r = redScroll.getValue();
           int g = greenScroll.getValue();
           int b = blueScroll.getValue();
           redLabel.setText(" R = " + r);
           greenLabel.setText(" G = " + g);
           blueLabel.setText(" B = " + b);
           colorCanvas.setBackground(new Color(r,g,b));
           colorCanvas.repaint();  // Redraw the canvas in its new color.
       } // end adjustmentValueChanged
    
       
       public Insets getInsets() {
              // The system calls this method to find out how much space to
              // leave between the edges of the applet and the components that
              // it contains.  I want a 2-pixel border at each edge.
          return new Insets(2,2,2,2);
       }
       
    }  // end class RGBColorChooser

Conclusion

Congrats, you’ve gotten through this extensive guide on AWT.Color in Java. Now, handling interfaces will be much easier. Don’t forget to apply your knowledge by solving practice problems and CodeGym quizzes. Practice makes perfect so give sample problems your best shot!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION