I have a JProgressBar and want to be able to see it dynamically updated. The progress bar should be able to visibly move from one position to another, not just change without the bar visibly changing (think regular loading bars).
public static void dropHPBar(int before, int after) {
Thread.currentThread.sleep(50);
while (before > after) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
GameMain.gW.setHP(before);
b --;
}
and from GameMain.gW:
public void setHP(int x) {
hpBar.setValue(x);
}
Why is the progress bar not being visibly updated?
Calling Thread.sleep
in the EDT
(event dispatch thread) prevents UI updates. You need to use Swing Worker in order to archive proper concurrency.
From the Oracle website:
Swing consists of three kinds of threads:
Initial threads, the threads that execute initial application code.
The event dispatch thread, where all event-handling code is executed. Most code that interacts with the Swing framework must also execute on this thread.
Worker threads, also known as background threads, where time-consuming background tasks are executed.
Tasks on the event dispatch thread must finish quickly; if they don't, unhandled events back up and the user interface becomes unresponsive.