JProgressBar并没有完全填满

时间:2014-12-11 20:15:49

标签: java swing swingworker jprogressbar

我有JProgressBar我已将最大值设置为150.使用javax.swing.Timer,我更新进度条并将time变量增加1.问题是time达到100后,进度条将不再更新,并保持在以下位置:

JProgressBar 2/3 filled

为什么会这样?有什么方法可以解决这个问题吗?

public class Test {
    int time = 0, duration = 150;
    JProgressBar progressBar;
    Timer timer;

    public Test() {
        GridBagLayout layout = new GridBagLayout();
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.BOTH;

        JFrame frame = new JFrame();
        frame.setLayout(layout);
        constraints.gridwidth = GridBagConstraints.REMAINDER;

        timer = new Timer(98, new ActionListener() {
            public void actionPerformed(ActionEvent ev) {
                time++;

                if (time == duration) {
                    time = 0;
                    timer.stop();
                }
            }
        });
        timer.start();

        progressBar = new JProgressBar(0,duration);
        progressBar.setValue(0);
        progressBar.setStringPainted(false);
        layout.setConstraints(progressBar,constraints);
        frame.add(progressBar);


        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

        ProgressBarUpdater pbUpdater = new ProgressBarUpdater();
        pbUpdater.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent ev) {
                progressBar.setValue(time);
            }
        });
        pbUpdater.execute();
    }

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

    public class ProgressBarUpdater extends SwingWorker<Void,Void> {
        @Override
        public Void doInBackground() {
            setProgress(0);
            while (time <= duration)
                setProgress(Math.min(time,duration));
            return null;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您的问题是,工作人员setProgress()的等级为0到100。

执行此更改,它将按预期工作:

public class ProgressBarUpdater extends SwingWorker<Void,Void> {
    @Override
    public Void doInBackground() {
        setProgress(0);
        while (time <= duration)
            setProgress((Math.min(time,duration) * 100) / duration); // convert to percent
        return null;
    }
}