In the last lesson, we used a number of colors predefined by Java: Color.red, Color.green, Color.magenta, etc. (for a complete list, go here). In this lesson, we learn how to create arbitrary colors, by specifying an RGB value. The example applets below generate spectrums of color and draw something with them.
The source code for the first applet:
(Download the below file: DrawingWithColor1.java)
import java.applet.*; import java.awt.*; public class DrawingWithColor1 extends Applet { int width, height; int N = 25; // the number of colors created Color[] spectrum; // an array of elements, each of type Color Color[] spectrum2; // another array public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); // Allocate the arrays; make them "N" elements long spectrum = new Color[ N ]; spectrum2 = new Color[ N ]; // Generate the colors and store them in the arrays. for ( int i = 1; i <= N; ++i ) { // The three numbers passed to the Color() constructor // are RGB components in the range [0,1]. // The casting to (float) is done so that the divisions will be // done with floating point numbers, yielding fractional quotients. // As i goes from 1 to N, this color goes from almost black to white. spectrum[ i-1 ] = new Color( i/(float)N, i/(float)N, i/(float)N ); // As i goes from 1 to N, this color goes from almost pure green to pure red. spectrum2[ i-1 ] = new Color( i/(float)N, (N-i)/(float)N, 0 ); } } public void paint( Graphics g ) { int step = 90 / N; for ( int i = 0; i < N; ++i ) { g.setColor( spectrum[ i ] ); g.fillArc( 0, 0, 2*width, 2*height, 90+i*step, step+1 ); g.setColor( spectrum2[ i ] ); g.fillArc( width/3, height/3, 4*width/3, 4*height/3, 90+i*step, step+1 ); } } }
The resulting applet:
A second example:
(Download the below file: DrawingWithColor2.java)
import java.applet.*; import java.awt.*; import java.lang.Math; public class DrawingWithColor2 extends Applet { int width, height; int N = 25; Color[] spectrum; public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); spectrum = new Color[ N ]; // Generate the colors and store them in the array. for ( int i = 0; i < N; ++i ) { // Here we specify colors by Hue, Saturation, and Brightness, // each of which is a number in the range [0,1], and use // a utility routine to convert it to an RGB value before // passing it to the Color() constructor. spectrum[i] = new Color( Color.HSBtoRGB(i/(float)N,1,1) ); } } public void paint( Graphics g ) { int radius = width / 3; for ( int i = 0; i < N; ++i ) { // Compute (x,y) positions along a circle, // using the sine and cosine of an appropriately computed angle. double angle = 2*Math.PI*i/(double)N; int x = (int)( radius*Math.cos(angle) ); int y = (int)( radius*Math.sin(angle) ); g.setColor( spectrum[ i ] ); g.drawString( "Color", width/2+x, height/2+y ); } } }
The output: