我有一个 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;
}
}
}
最佳答案
您的问题是,worker 中的 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;
}
}
关于java - JProgressBar 没有完全填满,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27431633/