所以我想在鼠标单击时迭代颜色数组,当它到达数组末尾时返回到数组中的 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];
}
}
最佳答案
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
称为三元运算符。这是一个 3 步过程
- 提问:
index <= colors.length-1?
( boolean 值) - 设置一个值,如果问题为真则返回
- 设置一个值,如果问题为 false,则返回
我们的索引从 0 开始。由于 0 <= 9 (colors.length-1),它将返回索引。 currentColor = colors[index];
尽管如此,假设我们的索引为 10。由于我们的数组仅从 0 到 9,因此我们需要在使用它之前将其设置回 0。 currentColor = colors[index = 0];
关于java - 我如何迭代颜色数组,以便每次单击鼠标时颜色都会改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23186123/