swing - Java Timer Not Working -
for reason java timer not working in 1 of programs. whenever compile code, gives me following error:
exception in thread "awt-eventqueue-0" java.lang.illegalstateexception: task scheduled or cancelled @ java.util.timer.sched(timer.java:401) @ java.util.timer.scheduleatfixedrate(timer.java:328)
why this? (note: novice @ java timers)
//timer prerequisites timer timer = new timer(); timertask task = new timertask() { public void run() { system.out.println("we have waited 1 second."); } }; //check see if user has enetered while(!answered) { timer.scheduleatfixedrate(task, 0, duration); afk = true; incorrect += 1; answered = true; }
since noted in tag, should using swing
timer, instead of using java.util.timer
.
please have @ sample example:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class swingtimerexample { private string[] questions = { "how you?", "how day?", "will work tonight?" }; private jlabel questionlabel; private buttongroup radiogroup; private jradiobutton yesradiobutton; private jradiobutton noradiobutton; private int counter; private static final int gap = 5; private timer timer; private actionlistener timeractions = new actionlistener () { @override public void actionperformed ( actionevent ae ) { ++counter; counter %= questions.length; questionlabel.settext ( questions [ counter ] ); if ( counter == questions.length - 1 ) { ( ( timer ) ae.getsource () ).stop (); } } }; public swingtimerexample () { counter = 0; } private void displaygui () { jframe frame = new jframe ( "swing timer example" ); frame.setdefaultcloseoperation ( jframe.dispose_on_close ); jpanel contentpane = new jpanel (); contentpane.setborder ( borderfactory.createemptyborder ( gap, gap, gap, gap ) ); contentpane.setlayout ( new borderlayout ( gap, gap ) ); jpanel labelpanel = new jpanel (); questionlabel = new jlabel ( questions [ counter ], jlabel.center); labelpanel.add ( questionlabel ); jpanel radiopanel = new jpanel (); yesradiobutton = new jradiobutton ( "yes" ); noradiobutton = new jradiobutton ( "no" ); radiogroup = new buttongroup (); radiogroup.add ( yesradiobutton ); radiogroup.add ( noradiobutton ); radiopanel.add ( yesradiobutton ); radiopanel.add ( noradiobutton ); contentpane.add ( labelpanel, borderlayout.center ); contentpane.add ( radiopanel, borderlayout.page_end ); frame.setcontentpane ( contentpane ); frame.pack (); frame.setlocationbyplatform ( true ); frame.setvisible ( true ); timer = new timer ( 5000, timeractions ); timer.start (); } public static void main ( string[] args ) { runnable runnable = new runnable () { @override public void run () { new swingtimerexample ().displaygui (); } }; eventqueue.invokelater ( runnable ); } }
Comments
Post a Comment