Reputation: 457
In this program I am doing, I need to be able to fill shapes with random colors. I am confused on how to actually fill in the shape. I am able to generate a random color. I have looked around online and found some sources talk about implementing the Paint
interface and use the method setPaint()
on the shape you are wishing to draw and then invoke the fill
method. I tried this but was unsuccessful. Maybe I just had it wrong. Here is what I had.
Random rand = new Random();
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
Color randomColor = new Color (r, g, b);
This was in a constructor of a superclass where I actually have randomColor
as an attribute of the class. So to access that element in the subclass, I provide a basic getter that just returns the Color.
In the subclass I have this:
Rectangle2D.Double rectangle = new Rectangle2D.Double(getX(), getY(), getWidth(), height);
rectangle.setPaint(getColor());
rectangle.fill();
g2.draw(rectangle);
The error I am getting is something about typecasting rectangle
but any typecast I try it's not working. I'm not exactly sure how to fix this issue. Any ideas? Or is there an easier/better way to fill a shape with a random color? Thanks.
Upvotes: 3
Views: 6921
Reputation: 324108
I need to be able to fill shapes with random colors
Then you should create a class (ColoredShape) that contains two properties:
Then you can create an ArrayList to hold instances of this class.
ArrayList<ColoredShape> shapes = new ArrayList<ColoredShape>();
shapes.add( new ColoredShape(aShape, generateRandomColor());
shapes.add( new ColoredShape(anotherShape, generateRandomColor());
Then in the paintComponent() method of your panel you iterate through the ArrayList and paint all the shapes:
for (ColoredShape shape: shapes)
{
g2.setColor(shape.getColor());
g2.draw(shape.getShape());
}
For a working example of this approach check out the DrawOnComponent
example found in Custom Painting Approaches.
Upvotes: 2
Reputation: 35011
You should be calling the methods you are calling on the rectangle on the Graphics2D
Rectangle2D.Double rectangle = new Rectangle2D.Double(getX(), getY(), getWidth(), height);
g2.setPaint(getColor());
g2.fill(rectangle);
g2.draw(rectangle);
Upvotes: 2