实现setNextColor()函数

时间:2014-10-15 01:25:52

标签: java colors

我想以某种方式调用我的程序setNextColour();(java.awt.Color)的函数,以便每次调用它时都会分配一个新颜色,但我不知道如何这样做。

也许列出颜色顺序的枚举,每次调用它我都会在枚举中得到下一个颜色?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

public enum Color {
    BLUE,
    GREEN,
    RED,
    YELLOW;

    public Color next() {
        return Color.values()[ (this.ordinal() + 1) % Color.values().length ];
    }
}

使用Color#next()将遍历所有Color并最终返回到开头,当它到达最后一个时。

例如:

public static void main(String[] args) {
    Color currentColor = Color.BLUE;
    for(;;) {
        System.out.println(currentColor);
        currentColor = currentColor.next();
    }
}

...会输出:

BLUE
GREEN
RED
YELLOW
BLUE
GREEN
RED
YELLOW
BLUE
GREEN
RED
...

如果您想将其与实际的java.awt.Color对接,我建议您只需按以下步骤进行增强:

public enum ColourSet {
    BLUE(Color.BLUE),
    GREEN(Color.GREEN),
    RED(Color.RED),
    YELLOW(Color.YELLOW);

    private final java.awt.Color color;

    private ColourSet(java.awt.Color color) {
        this.color = color;
    }

    public ColourSet next() {
        return ColourSet.values()[ (this.ordinal() + 1) % ColourSet.values().length];
    }

    public java.awt.Color getColor() {
        return color;
    }

    public static void main(String[] args) {
        ColourSet current = ColourSet.BLUE;
        for(;;) {
            System.out.println(current.getColor());
            current = current.next();
        }
    }
}

以同样的方式,该代码现在将输出:

java.awt.Color[r=0,g=0,b=255]
java.awt.Color[r=0,g=255,b=0]
java.awt.Color[r=255,g=0,b=0]
java.awt.Color[r=255,g=255,b=0]
java.awt.Color[r=0,g=0,b=255]
java.awt.Color[r=0,g=255,b=0]
java.awt.Color[r=255,g=0,b=0]
java.awt.Color[r=255,g=255,b=0]
java.awt.Color[r=0,g=0,b=255]
java.awt.Color[r=0,g=255,b=0]
java.awt.Color[r=255,g=0,b=0]
...

答案 1 :(得分:0)

在以下代码中,函数getNextColor()将在每次调用时随机返回一种新颜色。

public class Test extends JApplet{

Random rdm = new Random();
JButton change = new JButton("Click Me");
@Override
public void init(){
    setSize(300, 300);
    add(change, BorderLayout.CENTER);
    change.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            change.setBackground(getNextColor());
        }
    });
}

private Color getNextColor(){
    return new Color(rdm.nextInt(255), rdm.nextInt(255), rdm.nextInt(255));
}

}