Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How do I generate a random color? Here's my code...

807606Apr 10 2007 — edited Apr 11 2007
I'm trying to color a rectangle one of four colors, randomly. I can't figure out what I'm doing wrong. Here's my code:


import javax.swing.*;
import java.awt.*;


public class Rectangle extends JComponent  {


	private static final long serialVersionUID = 1L;

	public Rectangle(int x, int y, int w, int h)  {
        super();
		setBounds(x, y, w, h);
        setBackground(Color.RED);
	}

    public void paint(Graphics g)  {
        g.setColor( getBackground() );
        g.fillRect(0, 0, getWidth()-1, getHeight()-1);
        repaint();
        paintChildren(g);
   }

    
}
Basically, I need "g.setColor( getBackground() );" to be one of four random colors. I have a seperate class that this is used for.

Here is some code I was throwing around, but it doesn't seem to work at all:
public void randomcolor(int too) {
	Random ran = new Random();
	too=ran.nextInt(4)+1;
	switch (too)	{
	case 1: color=Color.blue;
	break;
	case 2: color= Color.green;
	break;
	case 3:color=Color.orange;
	break;
	case 4: color=Color.green;
	break;
	default: System.out.println("wrong number, pick another ");
	}
	top.setBackground(color);
	left.setBackground(color);
	right.setBackground(color);
	bottom.setBackground(color);

}	
Any help would be amazing. Thanks!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 9 2007
Added on Apr 10 2007
17 comments
2,079 views