Is there any way to do this? This is for a simulator I'm making. I want it so that when the counter(numTimes) reaches 139, it stops the timer. I tried delcaring but no initializing the timer before the Action Listener and stopping the timer within the actionPerformed function, but it gave me an error. I don't want to use another method(but if it works better then I'm all for it), and the while loop at the bottom causes the program to freeze? How can I make this work?
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
numTimes++;
switch(m1values[numTimes])
{
case 1:
new Moves().L();
break;
case 2:
new Moves().Lprime();
break;
case 3:
new Moves().R();
break;
case 4:
new Moves().Rprime();
break;
case 5:
new Moves().F();
break;
case 6:
new Moves().Fprime();
break;
case 7:
new Moves().B();
break;
case 8:
new Moves().Bprime();
break;
case 9:
new Moves().U();
break;
case 10:
new Moves().Uprime();
break;
case 11:
new Moves().D();
break;
case 12:
new Moves().Dprime();
break;
default:
}
drawAndButtons.add(new graphics());
cubeSpace.repaint();
if(numTimes >= 139)
{
numTimes = 0;
m1going = false;
}
}
};
Timer timer = new Timer( 500 , taskPerformer);
timer.setRepeats(true);
timer.start();
startTime = System.currentTimeMillis();
m1going = true;
while(m1going = true)
{}
timer.stop();
The problem with the while loop is if it's executed within the context of EDT, it will stop the timer from been triggered
Instead, get rid of loop and stop the
Timer
within theActionListener
This is a 1-character typo. The while loop will never stop, because you typed
=
instead of==
. The reason this even compiles at all is because the expressionm1going = true
returns the value oftrue
as well as assigningtrue
tom1going
. The while loop requires a boolean, and that's what it gets.This is a common error in C/C++, because an
int
is a valid boolean. Normally, Java will catch this for you, and complain that you can't put anint
(or whatever) in a while loop, but if you make this mistake with aboolean
, it is not caught.