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

2 回答 2

11

如果我是,我只会随机化色调分量,而不是亮度,而不是饱和度。

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

会漂亮很多。

于 2013-07-17T10:17:28.593 回答
6

您可以使用java.util.Random类和构造函数,

当我尝试 label.setBackground(Color.CYAN) 时,我什至没有得到背景

这是因为label它不是不透明的。使其不透明以使背景可见。

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

您可以使用Color类中的任何构造函数。为了生成float值,您可以使用Math.random()r.nextFloat()

于 2013-07-17T10:08:45.797 回答