Search code examples
javagraphics2d

Want to set more than one color to a method setBackgroundColor()


I need one small advice on how to set more than one colour to a method setBackgroundColor, i managed to make more than one color but only if program randomly pick color but i want to set specific 4 or five colours,here is my part of the code: (so on selected object it changes color)

if (isSelected)
    style.setBackgroundColor (new Color ((float) Math.random(),
                                         (float) Math.random(),
                                         (float) Math.random()));
  else
    style.unsetBackgroundColor();

Solution

  • Since you want 4 or 5 specific colors what you could do is make a list.

    ArrayList<Color> colorList = new ArrayList<Color>();
    //Then you add any colors you want, although you would have to define them yourself.
    colorList.add(color1);
    

    After adding the colors to a color list, you would need a way to grab a random color. One way we could do this is by making a Random object and using it to find an Integer from 0 to the list's size.

    Random rand = new Random();
    int colorNum = rand.nextInt(colorList.size());
    

    Now that we have the actual number, we can simply access that index in the list.

    Color c = colorList.get(colorNum);
    //Now, assuming your code above works for one color, you could do your 
    style.setBackgroundColor(c);
    

    This way you can add any colors in or even make colors based on user request and it would handle any color as long as you add it to the list.