setColor question
Hi, newbie here with two questions. I'm trying to draw three different triangles, all within the bounds of a JPanel, each with a different and random color. This gives me exactly what I want, but all three triangles are the SAME random color.
Second question: the bounds are given to me by calling getWidth and getHeight, correct? Or do I have to account for the 5 pixel border on each side, plus the title bar? It seems to me to work fine the way I have it, except for the color problem.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import java.util.Random;
import javax.swing.JPanel;
publicclass TrianglesJPanelextends JPanel
{
publicvoid paintComponent(Graphics g)
{
super.paintComponent(g);
Random random =new Random();// get random numbers
Graphics2D g2d = (Graphics2D)g;
GeneralPath triangle =new GeneralPath();// create GeneralPath
for (int i = 0; i < 3; i++)
{
// make triangle
triangle.moveTo(random.nextInt(getWidth()), random.nextInt(getHeight()));
triangle.lineTo(random.nextInt(getWidth()), random.nextInt(getHeight()));
triangle.lineTo(random.nextInt(getWidth()), random.nextInt(getHeight()));
// close the shape
triangle.closePath();
// set random color
g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
// draw triangle
g2d.fill(triangle);
}
}
}

