I'm learning Java and programming for the first time. I'm using the BlueJ
environment.
I'm writing a program to draw polygons. I want to change color after every line has been drawn. To do this, I thought I would create an array of colors, then use a pseudo-random number generator to generate a value that would be used as the index to get a color from the array. I've included a snippet of code from the constructor method, as I've been told I need to create the array inside the constructor for this to work.
It should be noted that I've imported java.awt.Color, along with java.util.Random. I've also included
private Color[] colors;
as a field.
public PictureMaker()
{
world = new TurtleWorld(500, 500, "Picture Maker");
fred = new Turtle();
//Allocate the size of the array
colors = new Color[7];
//Initialize the values of the array
colors[0] = new Color(Color.red);
colors[1] = new Color(Color.blue);
colors[2] = new Color(Color.yellow);
colors[3] = new Color(Color.green);
colors[4] = new Color(Color.black);
colors[5] = new Color(Color.pink);
colors[6] = new Color(Color.orange);
}
Below is the code from the actual method that will be called to draw the polygon.
/**
* This method takes sides (int) as input and draws a polygon with that number of sides.
*/
public void drawPolygon(int sides)
{
world.dropIn(fred);
fred.penDown();
int angle = 360/sides;
int linesDrawn = 0;
while(linesDrawn < sides)
{
Random r = new Random();
int minColor = 0;
int maxColor = 10;
int R = r.nextInt(maxColor-minColor) + minColor;
fred.right(angle);
fred.forward(60);
linesDrawn += 1;
}
}
I haven't included anything to get the color from the array yet, as I can't get the array to work.
I'm getting an error message Incompatible types: java.awt.Color cannot be converted to int
.
I'm not sure why it doesn't work.
I hope this makes sense.
Please let me know if you need clarification, I'm new to using this site.
The Color
fields are already of type Color
- you don't need to call the Color
constructor. The compiler is complaining because there isn't a Color
constructor which takes a Color
parameter. I suggest you use the more conventionally-named capitalized ones, too - and initialize the array with an array initializer for simplicity:
colors = new Color[]
{
Color.RED, Color.BLUE, Color.YELLOW, Color.GREEN,
Color.BLACK, Color.PINK, Color.ORANGE
};
See more on this question at Stackoverflow