Question

Ok so this is a shape drawn with a random color, however I'd like that shape to stay that color while being repainted. Right now with this draw method it just draws a new random color every repaint() so it looks like a rainbow shape. How would I make it grab a random color then stick with that for that particular shape?

public void draw(Graphics g) {
    g.setColor(new Color(randomNum.nextInt(256), randomNum.nextInt(256), randomNum.nextInt(256)));
    g.fillOval((int)getX(),(int)getY(), getRadius(), getRadius());

}
Was it helpful?

Solution

By saving the color you're drawing. So you'll only randomly generate it once, and then keep using that color to redraw each time.

Either generate it before the draw like Color c = new Color(randomNum.nextInt(256), randomNum.nextInt(256), randomNum.nextInt(256)); or only generate the variable and test if it has been initialized in your draw method. If it hasn't (the first time running your code), you generate a random color, if it has been initialized, you just skip generating the color and go straight to your g.fillOval

OTHER TIPS

You keep a list of shapes. every shape has his color and radius.

when repaint, you draw every shape in the list.

static class OvalShape {Color color; int radius;}
List<OvalShape> shapeList = new ArrayList<>();

public void draw(Graphics g) {
    for(Shape s : shapeList) {
        g.setColor(s.color);
        g.fillOval((int)getX(),(int)getY(), s.radius, s.radius);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top