java - Handling GUI with SWING with multithreading when the GUI does not update informations -
so have desktop application designed using mvc pattern inspired this tutorial (but modified). application needs copy list of file directory another. update gui after every file copied.
first of let me show code. in model have dummy method (not real method logic behind same):
public void dummymethod(integer k) throws interruptedexception{ for(int i=0;i<10;i++){ system.out.println(i); thread.sleep(1000); this.firepropertychange(defaultcontroller.backup_dummy, i-1, i); } }
in view have this:
@override public void modelpropertychange(propertychangeevent evt) { // ....... else if( evt.getpropertyname().equals( defaultcontroller.backup_dummy ) ){ system.out.println("what?"); this.dummy.settext(evt.getnewvalue().tostring()); } }
as can imagine what? printed every time gui not updated until loop has finished thing. that's classic problem when you're working swing , edt , i've read on oracle site article/tutorial don't think need use swingworker. need update single component on gui.
do not use event dispatch thread long running operation. should start thread long running operation such file copying. if need update gui worker thread, should use swingutilities.invokelater or swingutilities.invokeandwait methods..
as example ;
final jlabel label = new jlabel(); jbutton button = new jbutton(); button.addactionlistener(new actionlistener() { public void actioperformed(actionevent ev) { thread workerthread = new thread() { public void run() { //do long running job update ui swingutilities.invokelater(new runnable() { public void run(){ label.settext("operation has finished"); } }); } }.start(); } });
Comments
Post a Comment