所以我想在鼠标点击时迭代一系列颜色,当它到达数组末尾时,返回数组中的0空格。
private Color _color = Color.BLACK;
private Color[] _arrayOfColors = new Color[]{Color.GREEN, Color.RED, Color.BLUE, Color.BLACK};
@Override
public void paint(Graphics g)
{
g.setColor(_color);
g.drawRect(_x, _y, _size, _size);
}
@Override
public void mousePressed(MouseEvent mev)
{
for(int i = 0; i<_arrayOfColors.length; i++)
{
_color = _arrayOfColors[i];
}
}
答案 0 :(得分:1)
Color[] colors = new Color[10]; //your array of colors
Color currentColor; //current color being displayed
int index = 0; //IMPORTANT: prevents your loop from starting at 0 each time
public void mousePressed(MouseEvent e) {
currentColor = colors[index <= colors.length-1? index : index = 0]; //picks next color
index++; //increases index (prepares for next mouse click)
repaint(); //paint with new color
}
public void paint(Graphics g) {
g.setColor(currentColor);
g.drawRect(_x, _y, _size, _size);
}
currentColor = colors[index <= colors.length-1? index : index = 0];
一开始可能看起来很棘手,但让我分解一下:
index <= colors.length-1? index : index = 0
被称为三元运算符。这是一个三步过程
index <= colors.length-1?
(布尔)我们的索引从0开始。由于0 <= 9(colors.length-1),它将返回索引。 currentColor = colors[index];
虽然,假设我们的索引是10.因为我们的数组只从0到9,我们需要在使用它之前将其设置为0。 currentColor = colors[index = 0];
答案 1 :(得分:0)
声明一个属性来跟踪当前颜色的索引:
private int index = 0;
然后,在mousePressed
事件处理程序中,增加此索引,处理可能的ArrayIndexOutOfBoundsException
:
@Override
public void mousePressed(MouseEvent mev) {
_color = _arrayOfColors[index];
index = (index + 1) % _arrayOfColors.length;
}