java - Swing Timer issue - stop Timer -
i have been trying stop timer , solve days now, unfortunately no luck, hope able help.
the idea use timer click button increases value in text field have timer in start button , wish stop in stop button.
that's code have behind start button:
private void btstarttimeractionperformed(java.awt.event.actionevent evt) { javax.swing.timer tm = new javax.swing.timer(100, new actionlistener(){ public void actionperformed(actionevent evt) { btaddoneactionperformed(evt); } }); tm.start();
}
private void btstoptimeractionperformed(java.awt.event.actionevent evt) { }
you've got problem of scope in posted code: timer variable, tm, declared within start button's actionperformed method , is visible within method. cannot viable reference when outside of method. solution declare variable on class level private instance (non-static) variable, , call start()
on within start button's action listener. make variable visible throughout class, , stop button's listener should able call methods.
e.g.,
package pkg3; import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jbutton; import javax.swing.timer; public class timerdeclaration { private static final int delay = 1000; // tm2 variable visible throughout class private timer tm2 = new timer(delay, new timerlistener()); private jbutton btstarttimer1 = new jbutton("start timer 1"); private jbutton btstarttimer2 = new jbutton("start timer 2"); public timerdeclaration() { btstarttimer1.addactionlistener(e -> btstarttimer1actionperformed(e)); btstarttimer2.addactionlistener(e -> btstarttimer2actionperformed(e)); } private void btstarttimer2actionperformed(actionevent e) { tm2.start(); // tm2 visible throughout program } private void btstarttimer1actionperformed(actionevent e) { javax.swing.timer tm = new javax.swing.timer(100, new actionlistener() { public void actionperformed(actionevent evt) { // btaddoneactionperformed(evt); } }); tm.start(); // visible inside here!!! } private class timerlistener implements actionlistener { @override public void actionperformed(actionevent arg0) { // todo auto-generated method stub } } }
Comments
Post a Comment