-
Timer and TimerTask
I'm trying to use a Timer and a TimerTask that starts when a key is pressed, then stops when it is released. I'm not sure why I'm getting this error:
Exception in thread "AWT-EventQueue-1" java.lang.IllegalStateException: Task already scheduled or cancelled
I would think that it is started, then cancelled, started, cancelled, etc. Given this, how can I get this exception? Here are the relevant code fragments:
Code:
public Timer timer = new Timer();
public TimerTask
LUp = new TimerTask()
{
public void run()
{
if(LY > 35)
{
LY-=10;
}
}
},
LDown = new TimerTask()
{
public void run()
{
if(LY < 365)
{
LY+=10;
}
}
},
RUp = new TimerTask()
{
public void run()
{
if(RY > 35)
{
RY-=10;
}
}
},
RDown = new TimerTask()
{
public void run()
{
if(RY < 365)
{
RY+=10;
}
}
};
...
Code:
public void keyPressed(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_W:
timer.scheduleAtFixedRate(LUp, 0, 30);
break;
case KeyEvent.VK_S:
timer.scheduleAtFixedRate(LDown, 0, 30);
break;
}
switch (e.getKeyCode())
{
case KeyEvent.VK_UP:
timer.scheduleAtFixedRate(RUp, 0, 30);
break;
case KeyEvent.VK_DOWN:
timer.scheduleAtFixedRate(RDown, 0, 30);
break;
}
}
public void keyReleased(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_W:
LUp.cancel();
break;
case KeyEvent.VK_S:
LDown.cancel();
break;
}
switch (e.getKeyCode())
{
case KeyEvent.VK_UP:
RUp.cancel();
break;
case KeyEvent.VK_DOWN:
RDown.cancel();
break;
}
}
-
Is this a Swing application?
-
No, I'm doing it in an applet.