我有一個JTextField,如果內容無效,它將被清除。我希望背景閃爍一次或兩次以向用戶表明發生了這種情況。我曾嘗試:JTextField的閃爍顏色
field.setBackground(Color.RED);
field.setBackground(Color.WHITE);
但它是紅色的這樣一個短暫的時間,它不可能被看到。有小費嗎?
我有一個JTextField,如果內容無效,它將被清除。我希望背景閃爍一次或兩次以向用戶表明發生了這種情況。我曾嘗試:JTextField的閃爍顏色
field.setBackground(Color.RED);
field.setBackground(Color.WHITE);
但它是紅色的這樣一個短暫的時間,它不可能被看到。有小費嗎?
你需要擴大公共類Timer 做它像這樣:
private class FlashTask extends TimerTask{
public void run(){
// set colors here
}
}
您可以設置Timer
在執行任何間隔你希望創建閃爍的效果
從技術文檔:
public void scheduleAtFixedRate(TimerTask task, long delay, long period)
安排指定在指定的延遲後開始重複固定速率執行。
正確的解決方案几乎是由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);
買者被稱爲:代碼已經沒有編制,也沒有進行測試。
這是一個體面的解決方案,但我只希望它閃爍一次。問題更多的是背景沒有設置爲紅色足夠長的時間。 – rhombidodecahedron
通過閃光一次你的意思是改變顏色一秒鐘,然後改變回來並留在那裏?或只是改變顏色並保持這種顏色,直到滿足條件? 「 –
」沒有設置爲紅色足夠長的時間「你的意思是你需要幫助編輯更改的時間間隔? –