2013-07-17 37 views
3

我想爲Java中的JLabel生成隨機顏色。 JLabel將每100毫秒更改一次背景,並且背景必須是隨機的。這個怎麼做?如何在Java中生成隨機顏色?

我想到使用javax.swing.Timer類來做到這一點。看,我stumped.I甚至不是得到一個背景時,我已經試過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? 
    } 
}); 
+1

請在您發佈之前搜索! – user12458

+0

@JavaTechnical我搜索,但我沒有找到它! –

+0

搜索條件是什麼?我建議爲'[java]顏色隨機'。 –

回答

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

+0

這不是編譯! :( –

+0

爲什麼?錯誤是什麼? – user12458

+0

我對Timer的引用不明確 –

11

如果我是,我只會隨機化色調分量,而不是亮度,而不是飽和度。

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

它會更漂亮。