Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Example Java Swing Graphics2D How to show Rainbow Colors

Related Tutorials


 
 

Share on Google+Share on Google+

How to show Rainbow Colors

Advertisement
The Rainbow consists of seven colors known as VIBGYOR i.e. violet, indigo, blue, green, yellow, orange and red color.

How to show Rainbow Colors

     

This section illustrates you how to show all the seven colors of colors.

The Rainbow consists of seven colors known as VIBGYOR i.e. violet, indigo, blue, green, yellow, orange and red color. We are providing you an example which shows all the seven colors of rainbow.

All the visible colors can be obtained by the primary colors red, green and blue. Therefore we have defined red, green and blue colors. The height and width of image is defined.

 Following code draws the image of seven colors.

g.drawImage(bufferedImage, 0, 0, this)

Here is the code of ShowRainbowColors.java 

import javax.swing.*;
import java.awt.event.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

public class ShowRainbowColors extends JComponent {
  BufferedImage bufferedImage;

  public void initialize() {
  int wd= getSize().width;
  int ht = getSize().height;
  int[] data = new int[wd * ht];
  int index = 0;
  for (int j = 0; j < ht; j++) {
  int red = (j * 255) / (ht - 1);
  for (int k = 0; k < wd; k++) {
  int green = (k* 255) / (wd - 1);
  int blue = 128;
  data[index++] = (red << 16) | (green << 8) | blue;
  }
  }
  bufferedImage = new BufferedImage(wd, ht, BufferedImage.
   TYPE_INT_RGB);

  bufferedImage.setRGB(00, wd, ht, data, 0, wd);
  }
  public void paint(Graphics g) {
  if (bufferedImage == null)
  initialize();
  g.drawImage(bufferedImage, 00this);
  }
public static void main(String[] args) {
  JFrame frame = new JFrame("Show Rainbow Colors");
  frame.getContentPane().add(new ShowRainbowColors());
  frame.setSize(450300);
  frame.setLocation(100100);
  frame.addWindowListener(new WindowAdapter() {
  public void windowClosing(WindowEvent event) {
  System.exit(0);
  }
  });
  frame.setVisible(true);
  }
}

Output will be displayed as:

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 7, 2008

Related Tutorials

Discuss: How to show Rainbow Colors  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com