An example of how to manipulate colors to make a lovely rainbow.
public class RainBowColorGenerator
{
private static final int NR255 = 255;
private static final int YELLOW_TRESHOLD = 200;
private int r;
private int g;
private int b;
public RainBowColorGenerator()
{
this(0, NR255, 0);
}
/**
* Extra constructor so you can start with your own color in stead of the default green.
* @param red the red component
* @param green the green component
* @param blue the blue component
* @see java.awt.Color
*/
public RainBowColorGenerator(int red, int green, int blue)
{
this.r = red;
this.g = green;
this.b = blue;
}
/**
* Makes the next Color.
* @return a Color
*/
public Color nextColor()
{
nextRGB();
return makeColor();
}
/**
* Makes the next Color with a bigger change then the unparametrized nextColor method.
* @param jump the number of steps that should be taken, use 256 if you only want the primary colors.
* @return a Color , yes indeed a color.
*/
public Color nextColor( int jump )
{
for (int i = 0; i < jump; i++)
{
nextRGB();
}
return makeColor();
}
/**
* Makes the next Color with a bigger change then the unparametrized nextColor method.
* @param jump the number of steps that should be taken, use 256 if you only want the primary colors.
* @return a Color , that will be never be really close to yellow.
*/
public Color nextNonYellowColor( int jump )
{
Color color = nextColor(jump);
while ( color.getRed() > YELLOW_TRESHOLD && color.getGreen() > YELLOW_TRESHOLD )
{
color = nextColor(jump);
}
return color;
}
private void nextRGB()
{
if ( r == NR255 && g < NR255 && b == 0 )
{
g++;
}
if ( g == NR255 && r > 0 && b == 0 )
{
r--;
}
if ( g == NR255 && b < NR255 && r == 0 )
{
b++;
}
if ( b == NR255 && g > 0 && r == 0 )
{
g--;
}
if ( b == NR255 && r < NR255 && g == 0 )
{
r++;
}
if ( r == NR255 && b > 0 && g == 0 )
{
b--;
}
}
private Color makeColor()
{
return new Color(r, g, b);
}
public static void main( String[] args )
{
final RainBowColorGenerator bow = new RainBowColorGenerator();
JFrame frame = new JFrame(RainBowColorGenerator.class.toString());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel mainpanel = new JPanel()
{
@Override
public void paint( Graphics g )
{
super.paint(g);
int w = getWidth();
int h = getHeight();
for (int i = 0; i< w; i++)
{
g.setColor(bow.nextColor(2));
g.drawLine(i,0,i,h);
}
}
};
frame.getContentPane().add(mainpanel);
//noinspection MagicNumber
frame.setSize(800, 800);
frame.setVisible(true);
}
}