Search code examples
javamultithreadingapplet

Java: How to resume motion of a moving object after pausing it once in java applet using keyboard events?


This is my code to move a circle along x axis in applet window. Its working fine. I used threads. When I press 's' it starts and 'p' it pauses, that's fine. Problem is, when I again press 's' after it pausing it once, it throws an Illegal thread state exception which I can't figure out how to correct.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class MovingCircle extends Applet implements KeyListener, Runnable {

  Thread t; //thread to control motion
  boolean flag; //variable to control pausing of circle
  int x=50;
  int y=50;
  char c;

  public void init(){
      setBackground(Color.cyan);
      addKeyListener(this);
  }

  public void start(){
    t = new Thread(this);
  }

  //starting point for thread
  public void run()
  {
    for(;;){
      try{
          Thread.sleep(1000);
          x = x+10;
          repaint();
          if(flag){
              break;
          } 
      } catch(Exception e){

        }
     }
   }

   public void paint(Graphics g){
      g.fillOval(x,y,50,50);
   }

  public void keyPressed(KeyEvent k) {      
    c = k.getKeyChar();
    if(c=='s') t.start();
    if(c=='p') flag = true;
  }

  public void keyReleased(KeyEvent k) {}


  public void keyTyped(KeyEvent k) {}
}

Solution

  • When you stop a thread, you can't restart it.

    For this example, put it in a loop and forego the multithreading entirely...