Search code examples
javaarrays2dgrid-layoutternary-operator

Ternary Operator for grid color in array to be a specific color (multiple conditions) Java


I am constructing a GUI to display a map using GridLayout and would like to display it in different colors. As of right now, I have it so if the number in the array equals 0, the color of that specific square will be black. If it's any other number, it will be gray. As you can see, that would be a very boring grid map to look at. Is there a way to take this line of code and make it so if each number could represent a color? For example, I would like 0 to equal black, 1 to equal gray, 2 to equal blue, 3 to equal red, 4 to equal green, etc.. This is what I have now.

Color color = data[r][c] == 0 ? Color.BLACK : Color.gray;

I know I could just use an if statement to determine which color gets put there based on the number but I know there's a way to do it using a ternary operator. Anyone know how? Thank you.


Solution

  • Declare this array:

    Color[] colors = {  
        Color.BLACK, Color.WHITE, Color.LIGHT_GRAY, Color.GRAY,
        Color.DARK_GRAY, Color.RED, Color.PINK, Color.ORANGE, 
        Color.YELLOW, Color.GREEN, Color.MAGENTA, Color.CYAN, Color.BLUE
    };
    

    The values of this array are all Color constants from Color.java and you can rearrange them.
    Now set the color like this:

    Color color = colors(data[r][c] % colors.length);
    

    for any integer value of data[r][c] that is >=0.