0
\$\begingroup\$

I wrote a program that animates two squares diagonally across the screen, from opposite sides. Used Timer object to do so. The squares collide with each other and also with the frame boundary to change directions. The problem is that I added a key listener to stop the animation when you press a particular key, and again restart the animation when you press the same key, but that does not seem to work. The animation is not stopping.

problematic part:-

 public Drawing(){

    t=new Timer(10,this);
    t.start();
    addKeyListener(this);
    setFocusable(true);
    if(flag==-1){
        t.stop();
    }
    if(flag==1){
        t.start();
    }
}

and this is the keyListener part that changes flag to 1 / -1 :-

public void keyPressed(KeyEvent arg0) {
    if(arg0.getKeyCode()==KeyEvent.VK_ENTER || arg0.getKeyCode()==KeyEvent.VK_ESCAPE){
        flag=-(flag);
    }
}

i also found out that the value of flag variable is changing perfectly with each keyPressed, but it is not stopping the timer.

\$\endgroup\$
1
  • \$\begingroup\$ This should be migrated to StackOverflow. \$\endgroup\$ Apr 2 '14 at 6:25
1
\$\begingroup\$

Your Drawing constructor checks flag and starts or stops the timer. However, the only code (that you've shown) that could ever set flag is in the keyPressed callback.

keyPressed is called when a key is pressed, and will modify flag appropriately, but no code will ever check flag again. The Drawing constructor already ran to completion, so unless there is code you haven't shown here, nothing will ever stop the timer. Presumably the animation only starts because you initialize flag to -1.

Why don't you just start and stop the timer inside keyPressed?

public void keyPressed(KeyEvent arg0) {
  if(arg0.getKeyCode()==KeyEvent.VK_ENTER || arg0.getKeyCode()==KeyEvent.VK_ESCAPE){
    if(t.isRunning()) { // presumably this method or a similar one exists
      t.stop();
    }
    else {
      t.start();
    } 
  }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.