Search for more details......

Changing Colors Using For Loops

Changing Colors Using For Loops

You can change color at the run-time to generate different colors. Following example shows how to do it Java.



Many computer languages as well as Java, use three or four integers to represent a color. There are many color profile used in the world.

Example,

  • RGB(Red, Green, Blue),
  • CMYK(Cyan, Magenta, Yellow, Black),
  • RGBA(Red, Green, Blue, Alfa), act.   



 In programming, All sub elements of these profiles are represented by integer values.

Example,

       RGB-  Red      -Integer  (0-255)
                  Green   -Integer  (0-255)
                  Blue     -Integer   (0-255)

                As shown in the above example we can represent a RGB color using three integers. Value range is form zero  to 255. So, for red color, 255, 0, 0 and for Green color, 0, 255, 0 and for Blue color, 0, 0, 255.

When we want to create a mixed color we can give different values for these fields.

0,0,0 is black.
255,255,255 is white
255,255,0 is Yellow
100,100,100 is Gray


Change colors using loops.


for(int red=0;red<256;red+=10){

  for(int green=0;green<256;green+=10){

      for(int blue=0;blue<256;blue+=10){
          //Create new Colors for labels.
          Color color=new Color(red,green,blue);
          

          //Create Labels
          JLabel label=new JLabel(" Colored Text ");

          //Set Created Color to JLable.
          label.setColor(color);
                              
          add(label);


      }

  }    

}


Add this code into  your Java program that is created using a JFrame and run. You can see different colored texts.


No comments:

Post a Comment