我有一个JProgressBar,我需要在每次完成队列任务时使用以下代码设置新的minimum
,maximum
和progress
值:
this.progressBar.setMinimum(minimum);
this.progressBar.setMaximum(maximum);
this.progressBar.setValue(progress);
但是,我注意到有时,setMaximum(int)
方法似乎不起作用,因为进度条仍然使用旧的最大值。
然后我写了一些测试代码并运行它:
progressBar.setMaximum(10);
System.out.println(progressBar.getMaximum());
有时会按预期打印10
,有时会打印旧值:与10不同的任何内容。
我在Google和javadoc上花了好几个小时,试图在JProgressBar的父母身上拨打revalidate()
和repaint()
,什么都没有。我还试图调用Thread.sleep(10)
来等待AWT线程运行另一个任务并且没有工作。
有什么想法吗?
编辑:提供了更多代码:
/* Applet that construct the view and init a Thread. */
public class FastApplet extends Applet {
private JProgressBar progressBar;
private JPanel panel;
private Runnable runnable;
@Override
public void init() {
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
createAndShowGUI();
initThreads();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void createAndShowGUI() {
panel = new JPanel();
progressBar = new JProgressBar();
progressBar.setStringPainted(true);
panel.add(progressBar);
}
private void initThreads() {
runnable = new MyRunnable(progressBar);
Thread thread = new Thread(runnable);
thread.start();
}
}
/* Runnable that update progress and call setMaximum(int) on JProgressBar */
public class MyRunnable {
private int progress;
private final JProgressBar progressBar;
MyRunnable(JProgressBar progressBar) {
this.progressBar = progressBar;
}
@Override
public void run() {
// do the tasks and update the progressBar using progressBar.setValue(progress)
// when done, reset the progress bar with the a new maximum:
defineNewProgressBar(0, 0, newMaximum);
}
public void defineNewProgressBar(int progress, int minimum, int maximum) {
this.progress = progress;
Component component = progressBar.getParent();
JPanel panel = (JPanel) component;
this.progressBar.setMinimum(minimum);
this.progressBar.setMaximum(maximum);
this.progressBar.setValue(progress);
panel.revalidate();
panel.repaint();
}
}
答案 0 :(得分:2)
您在评论中写道,您没有从EDT致电setMaximum()
。你应该从EDT这样称呼它:
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
progressBar.setMaximum(10);
}
});
如果使用Java8,则可以使用lambda表达式执行此操作:
SwingUtilities.invokeLater(()->progressBar.setMaximum(10));
答案 1 :(得分:1)
您可以使用SafeProgressBarUpdaterThread:
progressBarUpdater = new SafeProgressBarUpdaterThread(progressBar);
//...
progressBarUpdater.setMaximum(maximum);
progressBarUpdater.setValue(value);
java.awt.EventQueue.invokeLater(progressBarUpdater);