随机颜色更改每次迭代

时间:2013-04-15 21:40:06

标签: java graphics

使用ArrayList时,我似乎无法弄清楚如何为for循环的每次迭代重置和重新应用随机颜色。每次我的XLeft位置改变时,我都会尝试重置并应用我的随机颜色。这只是我正在使用的一个类的一部分,而我的getMax()是由Scanner输入定义的。有什么建议吗?

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++;

    }
}

}

1 个答案:

答案 0 :(得分:0)

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

编辑(根据您的意见):

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++;

}