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(0, 0, wd, ht, data, 0, wd);
}
public void paint(Graphics g) {
if (bufferedImage == null)
initialize();
g.drawImage(bufferedImage, 0, 0, this);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Show Rainbow Colors");
frame.getContentPane().add(new ShowRainbowColors());
frame.setSize(450, 300);
frame.setLocation(100, 100);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
});
frame.setVisible(true);
}
}
|
Output will be displayed as:
Download Source Code