java - Swing timer synchronization -
i'm confused how swing timer work. in code below, want display 0~9 every 400ms in first text field when press start (once). after second text field display "finished".
public class main extends jpanel{ private static final long serialversionuid = 1l; private jbutton bstart; private jtextfield ttest; private jtextfield tnumber; main(){ bstart = new jbutton("start"); bstart.addactionlistener(new actionlistener(){ @override public void actionperformed(actionevent arg0) { // todo auto-generated method stub displaynumbers(); } }); ttest = new jtextfield(null, 30); tnumber = new jtextfield(" ", 30); tnumber.seteditable(false); this.setsize(300, 100); this.add(bstart); this.add(tnumber); this.add(ttest); } public void displaynumbers(){ new timer(400, new actionlistener() { int = 0; public void actionperformed(actionevent evt) { if(i<10){ tnumber.settext(integer.tostring(i)); i++; } else ((timer)evt.getsource()).stop(); } }).start(); ttest.settext("finished"); } public static void createandshowgui(){ jframe frame = new jframe("test"); frame.add(new main()); frame.setsize(400, 150); frame.setvisible(true); } public static void main(string args[]){ swingutilities.invokelater(new runnable(){ @override public void run() { // todo auto-generated method stub createandshowgui(); } }); } }
however, first displays "finished" before finishing displaying 0 ~ 9. think swing timer works in edt, "ttest.settext("finished");" executed after timer thread. why not work? how wait finishing displaying 0 ~ 9 print "finished"? thanks!
thanks answers. in fact want ask in general:
new timer(delay, new actionlistener() { public void actionperformed(actionevent evt) { dosomething(); } }).start(); doothers();
how let doothers() execute after dosomething()? (in cases, cannot put doothers() inside actionperformed function, answers mentioned).
the timer works concurrently. timer started, text set finished, , timer fires , first number appears.
to make timer display finished after finished, put ttest.settext("finished");
in else
clause of if(i<10)
.
Comments
Post a Comment