Java AWT Create Color Object


Program illustrating how to create a Java AWT Create Color Object and apply to graphics (strings)
import java.awt.*;
public class UsingColors extends Frame
{
  public void paint(Graphics g)
  {
    Color clr1 = new Color(200, 25, 100);
    g.setColor(clr1);
    g.drawString("Color set to graphics: " + g.getColor(), 50, 60);    
    g.drawString("Red component: " + clr1.getRed(), 50, 80);
    g.drawString("Green component: " + clr1.getGreen(), 50, 100);
    g.drawString("Blue component: " + clr1.getBlue(), 50, 120);
  }
  public static void main(String args[])
  {
    Frame f1 = new UsingColors();
    f1.setSize(300, 200);
    f1.setVisible(true);
  }
}

Java AWT Create Color Object

Color clr1 = new Color(200, 25, 100);
g.setColor(clr1);

A color object clr1 is created with 200 red component, 25 green component and 100 blue component. The color clr1 is applied to stings with setColor() method of Graphics class. drawString() draws a string on the frame at the specified coordinates. For a similar program with many font and color objects refer ColorsAndFonts.java.

Note: Observe another style of creating frame. Frame is created in the main() method instead of conventional constructor as done in other programs.

The frame you get do not close when clicked over the close icon on the title bar of the frame. It requires extra code close icon to work.

Leave a Comment

Your email address will not be published.