java - Downloading files in another thread and waiting for progress in main thread freezes JFrame from rendering -
i running download thread (installthread) files server (60kb) folder. after each file done downloading, thread class (installthread) changes value of percent
string variable current progress.
when files downloaded, done
boolean set true.
meanwhile, jpanel (running on global thread), checks current progress installthread (percent
), , sets text of displayed jlabel, installinglabel
current percentage.
the jpanel checks done
variable, causes while loop stop , application continues.
what doesn't work: while files downloading, jpanel not rendering (no background color, , jlabel not appear, though label visible before while loop started), , jframe freezes.
what works: files downloaded while jframe frozen, , when done
, jpanel's while loop breaks , application continues run.
finally, code:
framedisplay.java#draw_install(graphics2d g2d); (the jpanel-extending class)
installinglabel.setvisible(true); installthread installthread = new installthread(); installthread.start(); while (!installthread.done) { installinglabel.settext(installthread.percent); } /* continue on application */ dotchaser.getinstance().setstage(stage.main_menu);
installthread.java
int quota = 62000; int downloaded = 0; (string s : files) { // files array files download string url =<the server url > +s; file destination = new file( < destination folder>+s); downloadthread downloadthread = new downloadthread(url, destination); downloadthread.start(); // downloadthread downloading files. while (!downloadthread.done) { system.out.print(""); } downloaded += destination.length(); percent = (int) (((double) downloaded / (double) quota) * 100) + "%"; } done = true;
you're negating benefits of using background thread code this:
while (!installthread.done) { installinglabel.settext(installthread.percent); }
as tie swing event thread, freezing program.
instead, use type of notification system. myself, i'd use swingworker, add propertychangelistener
worker , respond newvalue of swingworker.statevalue.done
. use same propertychangelistener notified of changes in swingworker's progress property, , use update status of download.
please have at:
Comments
Post a Comment