Java Retrieve Color Information


Java Retrieve Color Information

Summary: Apart using colors in graphics, you can retrieve the information of the components of Color object. Comfortable to read in simple terms in "Java Retrieve Color Information".

We have learnt about Color class, how to create Color objects both RGB and HSB models and the predefined colors Java supports. Now let us explore the methods of Color class (we used earlier Color constructor to create a color). Using the methods getRed(), getGreen() and getBlue(), we can retrieve the color components of a Color object.

Supporting methods from java.awt.Color class
  • int getRed(): Returns the red component (content) of Color object.
  • int getGreen(): Returns the green component (content) of Color object.
  • int getBlue(): Returns the blue component (content) of Color object.
  • The range of values returned by the above methods is 0 to 255 (both inclusive).

    Supporting method of java.awt.Graphics class
  • Color getColor(): Returns the active color (in force) with the Graphics class.
  • The following program makes use of all the above 4 methods.

    import java.awt.*;
    public class RetrieveColorData extends Frame
    {
      Color clr;
      public RetrieveColorData()  
      {
        clr = new Color(200, 50, 150); 
    
        setTitle("Getting Color Info");
        setSize(450, 250);
        setVisible(true);
      }
      public void paint(Graphics g)  
      { 
        g.setColor(clr); 
        g.drawString("way2java.com", 60, 60);                         
    			      	
        g.drawString("RGB values of clr:", 60, 100);
        g.drawString(String.valueOf(clr.getRed()), 60, 130) ;
        g.drawString("Green Content: " + clr.getGreen(), 60, 150);
        g.drawString("" + clr.getBlue(), 60, 170);
    
        g.drawString("Current(in force) color info: " + g.getColor(), 60, 200);
      }		 
      public static void main(String args[ ])   
      {
        new RetrieveColorData();
      }
    }
    


    Java Retrieve Color Information
    Output screen of RetrieveColorData.java of Java Retrieve Color Information

    clr1.getRed(), clr.getGreen() and clr.getBlue() methods return the red, green and blue contents of Color object clr.

    g.getColor();

    The getColor() method of Graphics class returns the active color which is in force right now; here, it returns the clr object information (because it is set with setColor(clr)).

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

    Pass your comments to improve the quality of this tutorial "Java Retrieve Color Information".

    Leave a Comment

    Your email address will not be published.