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!