我有JProgressBar
我已将最大值设置为150.使用javax.swing.Timer
,我更新进度条并将time
变量增加1.问题是time
达到100后,进度条将不再更新,并保持在以下位置:
为什么会这样?有什么方法可以解决这个问题吗?
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;
}
}
}
答案 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;
}
}