java - SwingWorker ProgressBar -


i trying progress bar accurately reflect swingworker. can't figure out how it. got bar static animation until operation has completed want real active bar.

/*  * change template, choose tools | templates  * , open template in editor.  */ package frglauncher;  import java.io.file; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.randomaccessfile; import java.net.malformedurlexception; import java.net.url; import java.nio.channels.channels; import java.nio.channels.readablebytechannel; import java.util.enumeration; import java.util.jar.jarentry; import java.util.jar.jarfile; import java.util.logging.level; import java.util.logging.logger; import javax.swing.jlabel; import javax.swing.jprogressbar; import javax.swing.swingworker;  /**  *  * @author kyle-laptop  */ class downloadworker extends swingworker<string, object> {      private string game;     private jprogressbar bar;     private jlabel label;      public downloadworker(jprogressbar bar, string game, jlabel label) {         this.game = game;         this.bar = bar;         this.label = label;     }      @override     public string doinbackground() {          // download here         label.settext("test");         try {             // progressbar/install             system.out.println("filelocation:\n----------");             string url_location = "http://www.futureretrogaming.tk/gamefiles/professorphys.jar";             string local_file = ("\\" + game + "\\");             file localfile = new file(local_file);             if (localfile.exists()) {                 system.out.println("directory exists!");             }             else {                 system.out.println("directory doesn't exist! creating...");                 localfile.mkdir();                 if (localfile.exists()) {                     system.out.println("directory created!");                 }             }             system.out.println("localfile:\n-------");             system.out.println(local_file);             url website = new url(url_location);             readablebytechannel rbc = channels.newchannel(website.openstream());             fileoutputstream fos = new fileoutputstream(local_file + "\\professorphys.jar\\");             fos.getchannel().transferfrom(rbc, 0, long.max_value);             system.out.println("--------\ndone downloading\n---------");              randomaccessfile randomaccessfile = null;              file file = new file(local_file + "professorphys.jar\\");             jarfile jar = new jarfile(file);             enumeration enum1 = jar.entries();             while (enum1.hasmoreelements()) {                 jarentry file1 = (jarentry) enum1.nextelement();                 system.out.println("directory extract: " + local_file);                 system.out.println("\n" + file1.getname() + "\n");                 file f = new file(file1.getname());                 if (file1.isdirectory()) { // if it's directory, create                     f.mkdir();                     continue;                 }                 try (inputstream is1 = jar.getinputstream(file1)) {                     fileoutputstream fos1 = new fileoutputstream(f);                     while (is1.available() > 0) {  // write contents of 'is' 'fos'                         fos1.write(is1.read());                     }                     fos1.close();                 }             }         }         catch (filenotfoundexception ex) {             logger.getlogger(downloadworker.class.getname()).log(level.severe, null, ex);         }         catch (malformedurlexception ex) {             logger.getlogger(downloadworker.class.getname()).log(level.severe, null, ex);         }         catch (ioexception ex) {             logger.getlogger(downloadworker.class.getname()).log(level.severe, null, ex);         }         return "done";     }      @override     protected void done() {          // done         label.settext("download of " + game + "is done.");         system.exit(0);     } } 

several things:

  1. there 4 rules follow swingworker. can refer diagram: enter image description here.

so, code:

@override public string doinbackground() {     //download here     label.settext("test"); 

violates rule. label.settext() should moved constructor.

  1. to send "updates" swing components (like progress bar) want use process() method, invoke using publish() inside doinbackground(). second swingworker parameter reflects type of value want pass. i've attached 2 sscces. 1 passes integer process() method, other passes string. should give idea of what's going on.

sscce using integer:

import java.util.list; import java.util.concurrent.executionexception; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.joptionpane; import javax.swing.jpanel; import javax.swing.jprogressbar; import javax.swing.swingutilities; import javax.swing.swingworker;  /**  *  * @author ryan  */ public class test {      public static void main(string args[]) {         swingutilities.invokelater(new runnable() {             @override             public void run() {                 go();             }         });     }      public static void go() {         jframe frame = new jframe();         jpanel panel = new jpanel();         jlabel label = new jlabel("loading...");         jprogressbar jpb = new jprogressbar();         jpb.setindeterminate(false);         int max = 1000;         jpb.setmaximum(max);         panel.add(label);         panel.add(jpb);         frame.add(panel);         frame.pack();         frame.setsize(200,90);         frame.setlocationrelativeto(null);         frame.setvisible(true);         frame.setdefaultcloseoperation(jframe.exit_on_close);         new task_integerupdate(jpb, max, label).execute();      }      static class task_integerupdate extends swingworker<void, integer> {          jprogressbar jpb;         int max;         jlabel label;         public task_integerupdate(jprogressbar jpb, int max, jlabel label) {             this.jpb = jpb;             this.max = max;             this.label = label;         }          @override         protected void process(list<integer> chunks) {             int = chunks.get(chunks.size()-1);             jpb.setvalue(i); // last value in array care about.             system.out.println(i);             label.settext("loading " + + " of " + max);         }          @override         protected void doinbackground() throws exception {             for(int = 0; < max; i++) {                 thread.sleep(10); // illustrating long-running code.                 publish(i);             }             return null;         }          @override         protected void done() {             try {                 get();                 joptionpane.showmessagedialog(jpb.getparent(), "success", "success", joptionpane.information_message);             } catch (executionexception | interruptedexception e) {                 e.printstacktrace();             }         }     }    } 

sscce using string:

import java.util.list; import java.util.concurrent.executionexception; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.joptionpane; import javax.swing.jpanel; import javax.swing.jprogressbar; import javax.swing.swingutilities; import javax.swing.swingworker;  /**  *  * @author ryan  */ public class test2 {      public static void main(string args[]) {         swingutilities.invokelater(new runnable() {             @override             public void run() {                 go();             }         });     }      public static void go() {         jframe frame = new jframe();         jpanel panel = new jpanel();         jlabel label = new jlabel("loading...");         jprogressbar jpb = new jprogressbar();         jpb.setindeterminate(true);         panel.add(label);         panel.add(jpb);         frame.add(panel);         frame.pack();         frame.setsize(200,90);         frame.setlocationrelativeto(null);         frame.setvisible(true);         frame.setdefaultcloseoperation(jframe.exit_on_close);         new task_stringupdate(label).execute();     }      static class task_stringupdate extends swingworker<void, string> {          jlabel jlabel;         public task_stringupdate(jlabel jlabel) {             this.jlabel = jlabel;         }          @override         protected void process(list<string> chunks) {             jlabel.settext(chunks.get(chunks.size()-1)); // last value in array care about.             system.out.println(chunks.get(chunks.size()-1));         }          @override         protected void doinbackground() throws exception {              publish("loading step 1...");             thread.sleep(1000);             publish("loading step 2...");             thread.sleep(1000);             publish("loading step 3...");             thread.sleep(1000);             publish("loading step 4...");             thread.sleep(1000);              return null;         }          @override         protected void done() {             try {                 get();                 joptionpane.showmessagedialog(jlabel.getparent(), "success", "success", joptionpane.information_message);             } catch (executionexception | interruptedexception e) {                 e.printstacktrace();             }         }     } } 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -