swing - time counter in java using thread sleep and while loop -


i trying write code in java count time. used threadsleep make one-second delay. when run freezes time (3 seconds example) , shows result in ms. want know should prevent freezing , text label update each second.

import java.awt.*; import javax.swing.*;  public class test2 extends jframe {     private jbutton btn=new jbutton("start");     private jlabel lbl=new jlabel("00");       public test2() {         super("timer");         setlayout(new flowlayout());         setsize(400, 500);         add(lbl);         add(btn);         btn.addactionlistener(e->{                     startimer();                 });         setdefaultcloseoperation(jframe.exit_on_close);     }      private void startimer() {         long start=system.currenttimemillis();         int i=1;         while(i<4) {            try{                 thread.sleep(1000);                 long now=system.currenttimemillis();                 lbl.settext("the counter in ms:" + (now-start));                 i=i+1;             } catch(exception e){}         }      }        public static void main(string[] args) {           new test2().setvisible(true);       }   } 

you need use swing worker purposes:

class test2 extends jframe {     private jbutton btn=new jbutton("start");     private jlabel lbl=new jlabel("00");     public test2(){         super("timer");         setlayout(new flowlayout());         setsize(400, 500);         add(lbl);         add(btn);         setdefaultcloseoperation(jframe.exit_on_close);         btn.addactionlistener(e-> new swingworker<object, string>() {             @override             public object doinbackground() {                 long start = system.currenttimemillis();                 for(int = 0; < 4; i++) {                     try {                         thread.sleep(1000);                         publish("the counter in ms: " +                                 (system.currenttimemillis() - start));                     } catch(throwable e) {                         e.printstacktrace();                     }                 }                 return null;             }              @override             protected void process(final java.util.list<string> chunks) {                 if (!chunks.isempty()) {                     lbl.settext(chunks.get(chunks.size() - 1));                 }             }         });     } } 

Comments

Popular posts from this blog

inversion of control - Autofac named registration constructor injection -

verilog - Systemverilog dynamic casting issues -

ios - Change Storyboard View using Seague -