如何在java中重置JProgressBar?

时间:2016-04-22 08:06:11

标签: java jprogressbar

我有一个按钮,当我点击它时,它将启动progressbar。完成一次后,我希望重置进度条,如果我再次单击该按钮,它将重新开始。
这是我的代码:

else if (action == detectButton) {

            // pb.setVisible(true);

            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    pb.setValue(0);
                    pb.repaint();
                }
            });

            for (int i = 1; i <= 10; i++) {
                final int val = i;
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        pb.setValue(val);
                        pb.repaint();
                        try {
                            java.lang.Thread.sleep(100);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                });

            }

现在的问题是,当我第一次运行时运行正常,但在第二次尝试时它没有将进度条重置为0. 如何实际执行?

编辑: 我每次都重新绘制进度条,但我发现它不够平滑,无法显示10%发生在20%......

2 个答案:

答案 0 :(得分:0)

你的JProgressbar没有重置,因为它会在第一个Runnable完成后重新绘制。但是你的java.lang.Thread.sleep(2000);阻止了这一点。

答案 1 :(得分:0)

以下是完整示例,如何使用进度条:

    static IEnumerable<T[]> CartesianProduct<T>(IList<IList<T>> collections) {
        // this contains the indexes of elements from each collection to combine next
        var indexes = new int[collections.Count];
        bool done = false;
        while (!done) {
            // initialize array for next combination
            var nextProduct = new T[collections.Count];
            // fill it
            for (int i = 0; i < collections.Count; i++) {
                var collection = collections[i];
                nextProduct[i] = collection[indexes[i]];
            }
            yield return nextProduct;
            // now we need to calculate indexes for the next combination
            // for that, increase last index by one, until it becomes equal to the length of last collection
            // then increase second last index by one until it becomes equal to the length of second last collection
            // and so on - basically the same how you would do with regular numbers - 09 + 1 = 10, 099 + 1 = 100 and so on.

            var j = collections.Count - 1;
            while (true) {
                indexes[j]++;
                if (indexes[j] < collections[j].Count) {
                    break;
                }
                indexes[j] = 0;
                j--;
                if (j < 0) {
                    done = true;
                    break;
                }
            }
        }
    }