0

I'm trying to get an object to continue moving downwards after I release spacebar. It initially begins moving downward but after I press & release the spacebar the object just stays in place. I can't seem to get the object to continue falling after the KeyEvent is released.

public class htestnew extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
int x = 20, y = 20, vely =1;


public htestnew() {
 t.start();
 addKeyListener(this);
 setFocusable(true);
 setFocusTraversalKeysEnabled(false);
}


public void actionPerformed(ActionEvent e) {

if(y < 0)
{
 vely=0;
 y = 0;  
}

if(y > 305) //-70
{
 vely=0;
 y = 305;  
}

y += vely;
repaint();
}

public void keyPressed(KeyEvent e) {
 int code = e.getKeyCode();

  if (code == KeyEvent.VK_SPACE){
  vely = -1;
  }

}


public void keyTyped(KeyEvent e) {}

public void keyReleased(KeyEvent e) {
 vely=0;
}


}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
BSmyth
  • 3
  • 2
  • So, when `keyPressed` is called, you set `vely` to `-1`, when `keyReleased` is called, you set `vely` to `0` ... stopping the object. If you want it to keep falling to rest `valy` to `0` in `keyReleased`. Having said that, I'd discourage you from using `KeyListener` and would encourage you to use the [How to Use Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) API instead – MadProgrammer Jan 31 '16 at 01:49

1 Answers1

2

I can't seem to get the object to continue falling after the KeyEvent is released.

If you want the animation to continue to happen after you release a key, then you need to use a Swing Timer. When the key is pressed you start the Timer and the Timer will continue to generate events until you stop the Timer. Using this approach there is no need to handle the released event.

You would set your velocity to -1 and start the Timer. Then when the object reaches the bottom you would stop the Timer.

So basically the ActionListener would be used as the ActionListener for the Timer. You would just need to add the code to stop the Timer. Note, the source object of the ActionEvent when you use a Timer is the Timer so you can get a reference to the Timer from the ActionEvent.

Read the section from the Swing tutorial on Using Timers for more information.

camickr
  • 321,443
  • 19
  • 166
  • 288