簡體   English   中英

使用Thread.sleep()的paintComponent(Graphics g)的時間延遲不能按預期工作

[英]Time Delay using Thread.sleep() for paintComponent(Graphics g) not working as expected

我正在制作一個Animated ProgressBar,其中我使用了類javax.swing.Graphics多個fillRect()方法。
為了在繪制每個矩形后延遲,我使用Thread.sleep(500)方法進行延遲,(由許多論壇建議,為了延遲)。
問題是,在顯示每個“矩形”框之后,不執行0.5秒的延遲,而是在開始時采用所有矩形所需的全部延遲,然后顯示最終圖像,即進度條。
問題1
為了延遲每一個條形碼,我把延遲“ Thread.sleep(500) ”和條形碼“ fillRect() ”放在一個for() loop ,我想知道,為什么它需要所有的在開始時延遲,然后展示完成的ProgressBar。
問題2
如何更改我的代碼,以便延遲可以與每個矩形條同時發生,所以當我運行程序時,它應該生成一個動畫進度條。
碼:

import javax.swing.JOptionPane;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;

class DrawPanel extends JPanel
{
    public paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.setColor(new Color(71,12,3));
        g.fillRect(35,30,410,90);

        for ( int i=1; i<=40; i+=2)
        {
          Color c = new Color (12*i/2,8*i/2,2*i/2);
          g.setColor(c);
          g.fillRect( 30+10*i,35,20,80);

        try
          { Thread.sleep(500); } 
        catch(InterruptedException ex)
          { Thread.currentThread().interrupt(); }
        }
    }
}

class ProgressBar
{
    public static void main (String []args)
    {
        DrawPanel panel = new DrawPanel();
        JFrame app = new JFrame();
        app.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        app.add(panel);
        app.setSize(500,200);
        app.setVisible(true);
    }
}  

非常感謝您的幫助,謝謝。

不要阻止EDT(事件調度線程) - 當發生這種情況時,GUI將“凍結”。 而不是調用Thread.sleep(n)為重復的任務實現Swing Timer 有關更多詳細信息,請參閱Swing中的並發 另外請務必查看由@Brian鏈接的進度條教程。 它包含工作示例。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class DrawPanel extends JPanel
{
    int i = 0;
    public DrawPanel() {
        ActionListener animate = new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                repaint();
            }
        };
        Timer timer = new Timer(50,animate);
        timer.start();
    }
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.setColor(new Color(71,12,3));
        g.fillRect(35,30,410,90);

        Color c = new Color (12*i/2,8*i/2,2*i/2);
        g.setColor(c);
        g.fillRect( 30+10*i,35,20,80);

        i+=2;
        if (i>40) i = 0;
    }
}

class ProgressBar
{
    public static void main (String []args)
    {
        DrawPanel panel = new DrawPanel();
        JFrame app = new JFrame();
        app.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        app.add(panel);
        app.setSize(500,200);
        app.setVisible(true);
    }
}

我真的不會這樣做。 不應該像這樣使用Swing刷新線程。 您最好使用另一個線程(也許使用TimerTask ),並根據需要重新繪制矩形。

查看Oracle ProgressBar教程以獲取更多信息,代碼等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM