繁体   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