2016-12-28 62 views
0

我想閃爍的JButton的背景顏色,但只有'睡眠'它的工作。如何閃爍任何JComponent的背景顏色?

我的代碼:

@Override 
public void actionPerformed(ActionEvent e){ 

    if(!empty){ 
    }else{ 
    myButton.setBackground(Color.RED); 
    try {TimeUnit.MILLISECONDS.sleep(200);} catch (InterruptedException e2){} 
    myButton.setBackground(Color.LIGHT_GRAY); 
    try {TimeUnit.MILLISECONDS.sleep(200);} catch (InterruptedException e1) {} 
    myButton.setBackground(Color.RED); 
    try {TimeUnit.MILLISECONDS.sleep(200);} catch (InterruptedException e1) {} 
    myButton.setBackground(Color.LIGHT_GRAY); 
    } 
    } 
} 

編輯: 不能發佈整個代碼,那麼多行。 該按鈕是一個的GridBagLayout內:

myButton= new Jbutton("Button!"); 
myButton.setBackground(Color.White); 
myButton.setHorizontalAlignment(JTextField.CENTER);; 
myButton.setForeground(Color.black); 
GridBagConstraints gbc_myButton = new GridBagConstraints(); 
gbc_myButton.fill = GridBagConstraints.BOTH; 
gbc_myButton.gridx = 0; 
gbc_myButton.gridy = 1; 
gbc_myButton.gridwidth=3; 
panel.add(myButton, gbc_myButton); 

編輯2: 我剛找出它不設置在運行時任何顏色(具有或不具有任何延遲/睡眠)。

+0

你是什麼意思「只有'sleep'工作」? – ItamarG3

+0

延時工作,但顏色不變。 – tomyforever

+0

a)200毫秒很短,請嘗試更長的睡眠時間。 b)你在循環該代碼嗎? – ItamarG3

回答

2

你需要使用javax.swing.Timer做這樣的動畫。

final Button b = ...; 
final Color[] colors = ...; 
colors[0] = Color.RED; 
colors[1] = Color.LIGHT_GREY; 
ActionListener al = new ActionListener() { 
    int loop = 0; 
    public void actionPerformed(ActionEvent ae) { 
    loop = (loop + 1) % colors.length; 
    b.setBackground(colors[loop]); 
    } 
} 

new Timer(200, al).start(); 

注意:不是所有組件/ JComponents真正改變通過調用後臺的setBackground

+0

如何從我的類中檢索ActionListener對象?因爲你正在創建一個新的。如果我做新的時間(200,this),它會在actionPerformed()的第一行給我一個NullPointer。 – tomyforever

+0

我不明白你的問題。你在哪裏試圖檢索ActionListener?什麼是新時間(200,這個)?如果你在actionPerformed的第一行得到一個NullPointerException,這意味着你實際上沒有把顏色放到'colors'數組中 – ControlAltDel

+0

我認爲我必須使用實現我的類的ActionListener。在閱讀整個文檔之後https://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html我發現它是我的類的actionPerformed中的一個新的ActionListener。然後我嘗試了你的代碼,顏色正在改變,但循環不停止。 – tomyforever

0

問題是,當您睡覺UI線程(通過TimeUnit...sleep(x))時,它將無法重新呈現更改。我敢打賭,最後的顏色確實呈現。

你需要找到觸發顏色變化的另一種方法,看看定時器,特別是擺動定時器。

+0

(1-)Swing組件應在事件分派線程(EDT)上更新。所以你應該使用Swing Timer,而不是該鏈接中提到的其他計時器。 – camickr

+0

@camickr是的那些其他定時器不適合,謝謝 – weston