如何使用Swing计时器延迟进度条的加载 [英] How to use the Swing Timer to delay the loading of a progress bar

查看:85
本文介绍了如何使用Swing计时器延迟进度条的加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到一种在进度条上使用Swing计时器的方法.我尝试使用Thread.sleep(),但使用它时该应用程序崩溃了.有什么方法可以使用Swing计时器来代替Sleep()?

I need to find a way to use the Swing Timer with a progress bar. I tried using Thread.sleep(), but it crashed the app when I used it. Any ways to use the Swing Timer instead of the Sleep()?

public void piiEros(int dist)
{
    Pii pii = new Pii();
    pii.setVisible(true);
    for(int pc = 0;100 > pc; pc++)
    {
        try {
            Thread.sleep(dist/100);
        } catch (InterruptedException ex) {
            Logger.getLogger(Trav.class.getName()).log(Level.SEVERE, null, ex);
        }
        pii.pg.setValue(pc);
    }
    pii.dispose();
    o.Eros();
}

注意:Pii是带有进度条的课程.Dist是加载速度.Trav是该方法所在的类.Pc代表%,完成多少会显示在栏上.o.Eros打开另一个图形用户界面.

NOTES: Pii is a class with th Progress Bar. Dist is the speed at which it loads. Trav is the class the method is in. Pc stands for %, how much is done is displyed on the bar. o.Eros opens anotherr GUI.

推荐答案

从长远来看,使用 SwingWorker 可能更容易.它提供了许多有用的方法来更新UI(从事件调度线程的上下文中),同时允许在后台继续执行...

It's probably easier (in the long run) to use a SwingWorker. It supplies a number of useful methods for updating the UI (from the context of the Event Dispatching Thread) while allowing to continue executing in the background...

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestSwingWorker02 {

    public static void main(String[] args) {
        new TestSwingWorker02();
    }

    public TestSwingWorker02() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            JProgressBar pb = new JProgressBar();
            add(pb);

            new ProgressWorker(pb, 40).execute();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

    public class ProgressWorker extends SwingWorker<Void, Integer> {

        private int delay;
        private JProgressBar pb;

        public ProgressWorker(JProgressBar progressBar, int delay) {
            this.pb = progressBar;
            this.delay = delay;
        }

        @Override
        protected void process(List<Integer> chunks) {
            // Back in the EDT...
            pb.setValue(chunks.get(chunks.size() - 1)); // only care about the last one...
        }

        @Override
        protected Void doInBackground() throws Exception {
            for (int index = 0; index < 100; index++) {
                publish(index);
                Thread.sleep(delay);
            }
            return null;
        }

        @Override
        protected void done() {
            // Back in the EDT...
            //pii.dispose();
            //o.Eros();
        }

    }

}

SwingWorker 允许您分离逻辑.在 doInBackground 方法中,您可以专注于需要在EDT之外运行的那部分代码,可以将 published 更新更新回EDT和 process 分别.全部完成 后,您可以根据需要进行清理.

The SwingWorker allows you to separate the logic. In the doInBackground method you can focus on that part of the code that needs to operate outside the EDT, you can publish updates back to the EDT and process them separately. When it's all done you can clean up as required.

SwingWorker 还提供了进度监视功能,因此,在您的情况下,您将不必使用 publish / process 部分,如果您不想这样做的话.这将允许您将 PropertyChangeListener 附加到工作程序,而无需向其公开进度条.(但我为示例做了)

SwingWorker also provides a progress monitoring functionality, so, in your case, this would you wouldn't have to use the publish/process portion of the API if you didn't want to. This would allow you to attach a PropertyChangeListener to a the worker without the need to expose the progress bar to it. (But I did for the example)

public class ProgressWorker extends SwingWorker<Void, Integer> {

    private int delay;
    private JProgressBar pb;

    public ProgressWorker(JProgressBar progressBar, int delay) {
        this.pb = progressBar;
        this.delay = delay;
        // You can use a property change listener to monitor progress updates...
        addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if ("progress".equalsIgnoreCase(evt.getPropertyName())) {
                    pb.setValue((Integer)evt.getNewValue());
                }
            }

        });
    }

    @Override
    protected Void doInBackground() throws Exception {
        for (int index = 0; index < 100; index++) {
            setProgress(index);
            Thread.sleep(delay);
        }
        return null;
    }

    @Override
    protected void done() {
        // Back in the EDT...
        //pii.dispose();
        //o.Eros();
    }

}

这篇关于如何使用Swing计时器延迟进度条的加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆