Reputation: 441
I have a simple application that changes the color of a label when an action is performed.
When I click the button for my application(the action being performed), the color of the text of the label will continuously change on an interval set by the timer.
Now, what I am trying to accomplish is to have my button have the functionality of starting and stopping the change in color for the text of the label.
I am able to have it start, but I think there is a flaw in my logic when trying to stop execution of the change in color.
public void actionPerformed(ActionEvent e)
{
Timer timer = new Timer(500, timerListener);
while(!timer.isRunning())
{
if(!timer.isRunning())
{
button.setText("Stop");
timer.start();
}
else
{
timer.stop();
button.setText("Start");
}
}
Without the contents following the "else" I am able to start the program, but not stop it.
Please review and help. Thanks!
Upvotes: 0
Views: 1707
Reputation: 11020
Well, the code above creates a new timer each time the method is invoked. So the reference to the old timer is lost, which is why calling stop()
has no effect.
(Sorry for also posting this as a comment, but after I typed it all in I realized it might be the entire answer, not just a note about programming style. So I added it as an answer.)
For comparison, here's some working code of mine that does something similar. Notice I only create a new timer in the case where I'm going to be starting a new timing event. The stop case just stops the existing timer, it never creates one.
@Override
public void actionPerformed( ActionEvent e )
{
if( timing ) {
timing = false;
timer.stop();
view.setStartButtonText( "start stting" );
view.setTimerLabel( "stopped" );
view.setBackground( Color.CYAN.darker() );
} else {
nanoTime = System.nanoTime();
view.setStartButtonText( "stop stting" );
timing = true;
timer = new javax.swing.Timer( 1000,
new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
long minuteTime = ( System.nanoTime() -
nanoTime ) /
( 60_000_000_000L );
view.setTimerLabel( minuteTime + " minutes" );
if( minuteTime > 50 )
if( darkBg ) {
view.setBackground( Color.PINK );
darkBg = false;
} else {
view.setBackground( Color.PINK.
darker() );
darkBg = true;
}
}
} );
timer.setRepeats( true );
timer.start();
}
}
Upvotes: 2