I got a java progressbar which loads perfectly, but I can't see the process, only the result. (when the bar finished loading) I want to see every percentage of the progress. When I run the code, the frame appears but the progressbar doesn't, only when it's on 100%. Where's the problem?
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
JFrame f = new JFrame("JProgressBar Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
progressBar = new JProgressBar();
progressBar.setStringPainted(true);
Border border = BorderFactory.createTitledBorder("Reading...");
progressBar.setBorder(border);
content.add(progressBar, BorderLayout.CENTER);
f.setSize(300, 100);
f.setVisible(true);
progressBar.setValue(0);
inc(); //fill the bar
//It fills, but I can't se the whole loading...
}
//Here's the filling path
public static void inc(){
int i=0;
try{
while (i<=100){
progressBar.setValue(i+10);
Thread.sleep(1000);
i+=20;
}
}catch(Exception ex){
//nothing
}
}
Your GUI is not updated while you are running a long process in the GUI's thread, like filling a progress bar and sleeping some seconds.
Just emerge a thread, which will handle the long operation. Within this thread set the progress bar to the desired value within a SwingUtilities.invokeLater(new Runnable() {...}
.
Runnable r = new Runnable() {
public void run() {
int i=0;
try{
while (i<=100){
final int tmpI = i+10;
SwingUtilities.invokeLater(new Runnable(){
public void run() {
progressBar.setValue(tmpI);
}
});
Thread.sleep(1000);
i += 20;
}
} catch(Exception ex){
//nothing
}
}
};
Thread t = new Thread(r);
t.start();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.