Java Color Example

Colors play a very important role to get user’s attraction to the text (emphasize). To support colors, Java comes with java.awt.Color class. This Java Color Example changes rectangle color.

To create different colors, the Java AWT package comes with Color class. The Color class allows to create colors and at the same time gives 13 colors which can be used straightaway without creating object. They are red, green, blue, black, white, gray, lightGray, darkGray, cyan, orange, yellow, pink and magenta.

Following Java Color Example uses predefined colors as well as custom defined.
import java.awt.*;
public class JavaColorExample extends Frame
{
  public JavaColorExample()
  {
    setBackground(Color.cyan);   // sets predefined color cyan to background of frame

    setSize(450, 300);
    setVisible(true);
  }
  public void paint(Graphics g)
  {
    g.setColor(Color.red);           // predefined color
    g.drawRect(50, 100, 150, 100);   // rectangle outline is red color

    Color clr = new Color(200, 100, 150);
    g.setColor(clr);
    g.fillRect(220,100, 150, 100);   // rectangle filled with clr color 
  }
  public static void main(String args[])
  {
    new JavaColorExample();
  }
}

Java Color ExampleOutput Screenshot on Java Color Example

g.setColor(Color.red);
g.drawRect(50, 100, 150, 100);

Graphics is set to red color. red is a predefined color. Now the outline of the rectangle is drawn in red color. Know more on rectangle drawing at Drawing Right-angled Rectangles.

Color clr = new Color(200, 100, 150);
g.setColor(clr);
g.fillRect(220,100, 150, 100);

A Color object clr is created with red component 200, green component 100 and blue component 150. A rectangle is drawn with filled color clr1. See the screenshot.

More on Colors is given at Java AWT Color.

Leave a Comment

Your email address will not be published.