问题
I need to update jProgressBar in method which read from file and do some operations. I tried to update progress bar by this method:
public void progressUpdate(int percent) {
System.out.println("Update = "+percent);
synchronized (jMainProgressBar) {
jMainProgressBar.setValue(percent);
}
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jMainProgressBar.updateUI();
jMainProgressBar.repaint();
}
});
}
how ever this works only then when method is done. But if i continuously updating by this method then nothing happens.
Maybe some know how to improve this method?
It also would be nice for more suggestion Worker thread and else.
回答1:
You probably want to do
public void progressUpdate(final int percent) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
jMainProgressBar.setValue(percent);
}
});
}
回答2:
Don't use Thread. Use Timer. Refer the following:
- JProgressBar in Napkin look and feel is not working
- How to Use Progress Bars
- http://www.roseindia.net/java/example/java/swing/SwingProgressBar.shtml
- Read Concurrency in Swing for more information
回答3:
Based on the comments you provided (but not from the question!) you are performing heavy work on the Event Dispatch Thread (EDT). This blocks that thread and avoids any scheduled repaints to be performed. That is why you only see the update of your JProgressBar
after the work is finished, as that is the moment the EDT becomes available to perform the repaint.
The solution is already provided in the links posted by others but it basically comes down to:
- perform the work on a worker thread
- update the progress on the
JProgressBar
on the EDT
The two most common ways to achieve this are using a SwingWorker
or using SwingUtilities.invokeLater
from the worker thread.
All relevant links can be found in the answer of Yohan Weerasinghe
回答4:
Check this out
Timer barTimer;
barTimer=new Timer(100,new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
barvalue++;
if(barvalue>jProgressBar1.getMaximum())
{
/*
* To stop progress bar when it reaches 100 just write barTime.stop()
*/
barTimer.stop();
barvalue=0;
}
else
{
int a=(int)jProgressBar1.getPercentComplete();
jProgressBar1.setStringPainted(true);
jProgressBar1.setValue(barvalue);
}
}
});
barTimer.start();
Check the code at this link http://java23s.blogspot.in/2015/10/how-to-implement-progress-bar-in-java.html
来源:https://stackoverflow.com/questions/10587931/what-is-the-ways-updating-jprogressbar