gpt4 book ai didi

java - 如何延迟一个 while 循环?

转载 作者:行者123 更新时间:2023-12-01 17:46:38 24 4
gpt4 key购买 nike

我尝试过 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++;

}

}

最佳答案

您误解了图形的工作方式。您不能简单地通过稍后绘制某​​些内容来“延迟”渲染。这要么会延迟渲染线程,要么根本不会在屏幕上渲染。

这样做的原因是,在渲染完成之前,所有重绘组件的绘制都需要完成。但是,如果您逐步绘制线条,则整个过程将等到循环终止后程序才能继续(并显示线条)。将绘制方法视为相机的快门。您可以快速制作图片,而不是视频。因此,要让某些东西“移动”或缓慢绘制,您需要按顺序放置大量图片,就像电影中一样。

您真正想要的是定期重绘面板(您需要帧速率)。例如,如果您想以每秒接近 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();
}
}
}

关于java - 如何延迟一个 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54441193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com