Search code examples
javarandomcolorsjbuttonsetbackground

Color.getColor(String, int) - random color


I'm trying to set the random color of JButton object by:

button.setBackground(Color.getColor(null,(int) (Math.random() * 255 + 1)));

but it only produces different shades of blue. Thanks.


Solution

  • use the following:-

    int red = (int) (Math.random() * 256);
    int green = (int) (Math.random() * 256);
    int blue = (int) (Math.random() * 256);
    button.setBackground(new Color(red, green, blue));