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

标签 java loops 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++;

        }

    } 

最佳答案

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

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

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

相关文章:

java - 我不明白为什么要做这个 Action ?我只需要解释一下

java - 再次使用 Draw 与 Repaint

java - 关闭扫描器是强制性的吗?

java - 在 Java 8 中不使用预定义方法将集合转换为另一种集合类型

Javascript 提前退出循环

loops - 如何在 Julia 中实现递减循环?

python - 掷骰子程序的无限 while 循环问题

java - Spring 3.1 Web 应用程序问题

Python 两个整数循环,+1 到 A 直到 A=​​B

python - python 中的变量和不完整行为 "for"循环