【问题标题】:Updating the progress bar更新进度条
【发布时间】:2014-04-09 06:55:24
【问题描述】:

我有一个需要通过 GUI 调用的大程序。 GUI 有一个进度条,在用户按下开始按钮后需要更新(如 5% .... 10% )。 问题是执行的后台任务没有固定的执行时间。因此,以某种方式可以测量在 doInBackground() 方法中执行的任务的进度(我正在尝试使用 SwingWorker)。或者我应该使用不确定的进度条。 我无法清楚地理解 Oracle 教程页面上提供的示例,也找不到合适的页面来解释如何使用进度条。 任何帮助将不胜感激。

【问题讨论】:

  • @MemLeak 我的程序的输入没有固定的大小,因此执行时间会有所不同。该程序使用遗传算法,使用线程实现。
  • 对不起@user3313050 我不能那样做。但是你能解释一下“public void propertyChange(PropertyChangeEvent evt)”方法在给定的link 中是如何工作的吗?

标签: java swing swingworker jprogressbar


【解决方案1】:

根据问题,我会使用无限进度条

public class Indeterminate extends JProgressBar {

    private static final long serialVersionUID = -281761375041347893L;

    /***
     * initial the ProgressBar 
     */
    public IndeterminateProgressBar() {
        super();
        setIndeterminate(true);
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                setVisible(false);
            }
        });
    }

    /**
     * call this, if you start a long action
     */
    public void start() {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                setVisible(true);
            }
        });
    }

    /**
     * if you have finished, call this
     */
    public void end() {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                setVisible(false);
            }
        });
    }

}

这样使用:

ActionListener startButtonListener = new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {

        new Thread(new Runnable() {

            @Override
            public void run() {

                try {
                    progressBar.start();
                    // long operation

                } catch (Exception e) {
                    // handle excpetion
                } finally {
                    progressBar.end();

                }

            }
        }).start();

    }
};

【讨论】:

  • 谢谢你的回复我试试这个。
猜你喜欢
  • 2013-03-08
  • 2020-11-05
  • 1970-01-01
  • 2013-06-10
  • 2018-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多