3

I would like to generate a random color for JLabel in Java. The JLabel will be changing the background every 100 ms and the background has to be random. How to do this?

I thought of using javax.swing.Timer class to do this. See, i am stumped.I am not even getting a background when i have tried the label.setBackground(Color.CYAN)

JLabel l=new JLabel("Label");
Timer t=new Timer(2,new ActionListener(){
  public void actionPerformed(ActionEvent ae)
  {
       // what is the code here?
  }
});
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Say Off
  • 79
  • 1
  • 1
  • 8

2 Answers2

11

If I were, I would only randomize the hue component, not the brightness, not the saturation.

double hue = Math.random();
int rgb = Color.HSBtoRGB(hue,0.5,0.5);
Color color = new Color(rgb);

It will be much more pretty.

David
  • 1,138
  • 5
  • 15
6

You can use java.util.Random class and the constructor,

I am not even getting a background when i have tried the label.setBackground(Color.CYAN)

This is because the label is not opaque. Make it opaque for the background to be visible.

final JLabel label=new JLabel("Label");
        // Label must be opaque to display
        // the background
        label.setOpaque(true);

        final Random r=new Random();
        Timer t=new Timer(100,new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                Color c=new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256),r.nextInt(256));
                label.setBackground(c);
            }
        });
        t.start();

You can use any of the constructors in the the Color class. For generating float values you can use Math.random() or r.nextFloat()

JavaTechnical
  • 8,846
  • 8
  • 61
  • 97