2012-06-21 152 views
0

我有一個JTextField,如果內容無效,它將被清除。我希望背景閃爍一次或兩次以向用戶表明發生了這種情況。我曾嘗試:JTextField的閃爍顏色

field.setBackground(Color.RED); 
field.setBackground(Color.WHITE); 

但它是紅色的這樣一個短暫的時間,它不可能被看到。有小費嗎?

回答

2

你需要擴大公共類Timer 做它像這樣:

private class FlashTask extends TimerTask{ 
    public void run(){ 
     // set colors here 
    } 
} 

您可以設置Timer在執行任何間隔你希望創建閃爍的效果

從技術文檔:

public void scheduleAtFixedRate(TimerTask task, long delay, long period)

安排指定在指定的延遲後開始重複固定速率執行。

+0

這是一個體面的解決方案,但我只希望它閃爍一次。問題更多的是背景沒有設置爲紅色足夠長的時間。 – rhombidodecahedron

+0

通過閃光一次你的意思是改變顏色一秒鐘,然後改變回來並留在那裏?或只是改變顏色並保持這種顏色,直到滿足條件? 「 –

+1

」沒有設置爲紅色足夠長的時間「你的意思是你需要幫助編輯更改的時間間隔? –

6

正確的解決方案几乎是由eric來完成的,因爲Timer的ActionListener中的所有代碼都將在Swing事件線程中調用,這可以防止發生間歇性和令人沮喪的錯誤。例如:

public void flashMyField(final JTextField field, Color flashColor, 
    final int timerDelay, int totalTime) { 
    final int totalCount = totalTime/timerDelay; 
    javax.swing.Timer timer = new javax.swing.Timer(timerDelay, new ActionListener(){ 
    int count = 0; 

    public void actionPerformed(ActionEvent evt) { 
     if (count % 2 == 0) { 
     field.setBackground(flashColor); 
     } else { 
     field.setBackground(null); 
     if (count >= totalCount) { 
      ((Timer)evt.getSource()).stop(); 
     } 
     } 
     count++; 
    } 
    }); 
    timer.start(); 
} 

而且,它還將通過flashMyField(someTextField, Color.RED, 500, 2000);

買者被稱爲:代碼已經沒有編制,也沒有進行測試。

+0

+1 for'javax.swing.Timer' – trashgod

+0

和FYI:你應該使用Timer的原因以及爲什麼你看不到紅色的原因與我在[這個答案]中描述的差不多。 http://stackoverflow.com/questions/11088910/timing-with-swing-animation/11090056#11090056)。 – Robin

+2

+1不錯,在這個答案中,不要調用'setBackground(Color.WHITE)',它不是某些L&F的默認背景。 – Robin