0

While using an ArrayList, I can't seem to figure out how to reset and re-apply the random color for each iteration of the for loop. I am trying to reset and apply my random color every time my XLeft position is changed. This is only a section of one class I am using, and my getMax() was defined by a Scanner input. Any suggestions?

import java.util.ArrayList;
import java.util.Random;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;

public class BarChart {

private int width, height;
private ArrayList<Double> values = new ArrayList<Double>();
private Random generator = new Random();
int red = generator.nextInt(255);
int green = generator.nextInt(255);
int blue = generator.nextInt(255);
private Color randomColor = new Color(red, green, blue);


public BarChart(int aWidth, int aHeight) {

    width = aWidth;
    height = aHeight;

}

public void add(double inputValues) {
    values.add(inputValues);
}

public double getMax() {

    double max = values.get(0);

    for (int i = 1; i < values.size(); i++) {
        if ((values.get(i)) > max)
            max = values.get(i);

    }
    return max;
}

public void draw(Graphics2D g2) {

    int xLeft = 0;
    double barWidth = width / values.size();

    for (int i = 0; i < values.size(); i++) {

        double barHeight = (values.get(i) / getMax()) * height;
        Rectangle bar = new Rectangle(xLeft, height - ((int) barHeight),
                (int) barWidth, (int) barHeight);
        g2.setColor(randomColor);
        g2.fill(bar);
        xLeft = (int) (xLeft + barWidth);
        xLeft++;

    }
}

}

4

1 回答 1

0

听起来您在循环之前定义了一次随机颜色。这意味着当您运行循环时,它每次都使用相同的“随机颜色”。您需要将随机颜色的定义移动到循环中,以便它在每次迭代中运行。

编辑(根据您的评论):

public void draw(Graphics2D g2) {

int xLeft = 0;
double barWidth = width / values.size();

for (int i = 0; i < values.size(); i++) {

    double barHeight = (values.get(i) / getMax()) * height;
    Rectangle bar = new Rectangle(xLeft, height - ((int) barHeight),
            (int) barWidth, (int) barHeight);

    red = generator.nextInt(255); 
    green = generator.nextInt(255);
    blue = generator.nextInt(255);
    randomColor = new Color(red, green, blue);

    g2.setColor(randomColor);
    g2.fill(bar);
    xLeft = (int) (xLeft + barWidth);
    xLeft++;

}
于 2013-04-15T21:50:45.073 回答