简体   繁体   中英

drjava JFrame help object won't continue moving after KeyEvent button is released

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;
}


}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM