ᴘᴀɴᴀʏɪᴏᴛɪs
ᴘᴀɴᴀʏɪᴏᴛɪs

Reputation: 7529

Implementing a setNextColor() function

I want in some way to call a function of my program setNextColour(); (java.awt.Color) so that each time I call it a new color is assigned, but I'm not sure how to do this.

Maybe an enum listing the color order and each time I call it I get the next color in the enum?

Upvotes: 0

Views: 39

Answers (2)

Muhammad
Muhammad

Reputation: 7344

In the following code the function getNextColor() will return a new color randomly each time you call it.

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));
}

}

Upvotes: 0

ccjmne
ccjmne

Reputation: 9606

You could do something like this:

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

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

Using Color#next() would iterate through all your Colors and eventually go back to the beginning, when it would have reached the last one.

For example:

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

... would output:

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

If you want to interface it to actual java.awt.Colors, I'd suggest you to simply enhance it as follows:

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();
        }
    }
}

In the same way, that code would now ouput:

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]
...

Upvotes: 1

Related Questions