Results 1 to 3 of 3
Thread: Timer and TimerTask
- 04-07-2009, 11:29 PM #1
Senior Member
- Join Date
- Jan 2009
- Location
- NJ, USA
- Posts
- 183
- Rep Power
- 5
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:
...Java 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; } } };
Java 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; } }Last edited by AndrewM16921; 04-07-2009 at 11:31 PM.
-
Is this a Swing application?
- 04-07-2009, 11:40 PM #3
Senior Member
- Join Date
- Jan 2009
- Location
- NJ, USA
- Posts
- 183
- Rep Power
- 5
Similar Threads
-
Timer help
By Kinyo in forum New To JavaReplies: 15Last Post: 03-15-2009, 02:37 AM -
EJB Timer
By mrjunsy in forum Advanced JavaReplies: 0Last Post: 08-22-2008, 04:09 PM -
EJB Timer
By mrjunsy in forum New To JavaReplies: 0Last Post: 08-04-2008, 06:47 PM -
How to cancel an individual timer in spite of canceling whole timer
By Java Tip in forum java.utilReplies: 0Last Post: 04-04-2008, 02:46 PM -
TimerTask with a Date_Time
By kunta in forum Sun Java Wireless ToolkitReplies: 1Last Post: 05-31-2007, 10:17 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks