[英]How do I delay just an while loop?
我嘗試過Tread.sleep,但它會延遲整個程序,而不僅僅是循環。 我想在SFrame中畫一條線,但我希望它慢慢畫線。
public class Panel extends javax.swing.JPanel
{
int a=0;
int b=0;
public void paint(java.awt.Graphics g)
{
g.setColor(Color.GREEN);
g.fillRect(0,0,500,500);
g.setColor(Color.BLACK);
while( a<=500&&b<=500){
g.fillRect(a,b,5,5);
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {}
a++;
b++;
}
}
您誤解了Graphics
工作方式。 您不能簡單地通過稍后繪圖來“延遲”渲染。 這會延遲渲染線程,或者根本不會在屏幕上渲染。
這樣做的原因是,在完成渲染之前,所有重新繪制的組件的繪制都需要完成。 但是,如果您逐漸畫線,則整個過程將等待,直到循環終止,程序才能繼續(並顯示該線)。 將繪制方法想像成相機的快門。 您可以快速拍照,而不是視頻。 因此,要讓某些東西“移動”或緩慢繪制,您需要依次放置很多圖片,例如在電影中。
您真正想要的是定期重新繪制面板(您需要幀速率)。 因此,例如,如果您想以每秒接近30幀的速度進行渲染,則可以執行以下操作:
public class AutoUpdatedPanel extends javax.swing.JPanel {
Thread t;
float linePercent = 0f;
public AutoUpdatedPanel () {
t = new AutoUpdateThread();
t.start();
}
public void paint(java.awt.Graphics g) {
g.setColor(Color.GREEN);
g.fillRect(0, 0, 500, 500);
g.setColor(Color.BLACK);
int linePos = (int) 5 * linePercent;
g.fillRect(linePos, linePos, 5, 5);
}
public class AutoUpdateThread extends java.lang.Thread {
public void run() {
while (!isInterrupted()) {
try {
Thread.sleep(33);
} catch (InterruptedException e) {
// silent.
}
linePercent += .5f;
linePercent = math.min(linePercent, 100f);
AutoUpdatedPanel.this.repaint();
}
}
}
}
但是我建議使該行的增長基於時間:
...
public class AutoUpdateThread extends java.lang.Thread {
public void run() {
while (!isInterrupted()) {
try {
Thread.sleep(33);
} catch (InterruptedException e) {
// silent.
}
nowMillis = Calendar.newInstance().getTimeInMillis();
long timeOffset = nowMillis - start;
linePercent = (float) (.002d * timeOffset);
linePercent = math.min(linePercent, 100f);
AutoUpdatedPanel.this.repaint();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.