Multi-threaded java progress bar
Lets see how to make a multi threaded progress bar in java swing, using
net-beans ide.you might wonder why i use another thread to update the
progress bar while i still can use the main thread to do it.reason to
this is when it comes to real work progress bar update might freeze the
main gui due to waiting for other tasks to complete.so leaving main
thread alone and make new thread to do our task is all ways a wise idea.
first make a new desktop application project in net-beans, then add a new jframe form to the project.
now in ui edit mode add jprogressbar component from the pallet to the from (drag and drop).
add 2jbuttons to the form as well.rename buttons to "change value" and "start update".
In jframe class declare
private Thread PB;
private int PV = 0;
now in side "start update" button add the flowing code :
PB = new Thread(() -> {
for (;;) {
jProgressBar1.setValue(PV);
try {
PB.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(progressBarM.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
PB.start();
what this code does is, create a new thread and start it.in side thread it update the progress bar value for ever.to kep our program from freezing i have sleep the thread for some milliseconds.
now in " change value " button add this code :
PV = new Random().nextInt(100);
jProgressBar1.setString(String.valueOf(PV));
All it does is update the integer value from 1-100 randomly. each time user press the button it will choose a random number between 1-100.this part is equal to real task updating its progress.
in action : https://www.youtube.com/watch?v=qafbVvLv7ss&feature=youtu.be
download :https://github.com/stark9000/progress-bar-with-thread.git
now in ui edit mode add jprogressbar component from the pallet to the from (drag and drop).
add 2jbuttons to the form as well.rename buttons to "change value" and "start update".
In jframe class declare
private Thread PB;
private int PV = 0;
now in side "start update" button add the flowing code :
PB = new Thread(() -> {
for (;;) {
jProgressBar1.setValue(PV);
try {
PB.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(progressBarM.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
PB.start();
what this code does is, create a new thread and start it.in side thread it update the progress bar value for ever.to kep our program from freezing i have sleep the thread for some milliseconds.
now in " change value " button add this code :
PV = new Random().nextInt(100);
jProgressBar1.setString(String.valueOf(PV));
All it does is update the integer value from 1-100 randomly. each time user press the button it will choose a random number between 1-100.this part is equal to real task updating its progress.
in action : https://www.youtube.com/watch?v=qafbVvLv7ss&feature=youtu.be
download :https://github.com/stark9000/progress-bar-with-thread.git
No comments:
Post a Comment