0

I need to make an image bounce on the screen. I am trying to do this by shifting the image up 5 units, then taking a one second break, then shifting another 5 units up, etc. I am trying to shift up 5 times and then shifting down 5 times, with a one second break between each shift. I need help making the timer for one second so it acts like a break between each shift. I need to write the time() method.

public void moveIt(KeyEvent evt) throws InterruptedException {
    switch (evt.getKeyCode()) {
    case KeyEvent.VK_DOWN:
        myY += 0;
        break;
    case KeyEvent.VK_UP:
        for (int i = 1; i <= 10; i++) {
            if (i <= 5) {
                bounceUp();
            } else {
                bounceDown();
            }
            time();
        }
        break;
    case KeyEvent.VK_LEFT:
        myX -= 5;
        break;
    case KeyEvent.VK_RIGHT:
        myX += 5;
        break;
    }

    repaint();
}

Timer timer = new Timer();

public void bounceUp() throws InterruptedException {
    myY -= 10;
}

public void bounceDown() throws InterruptedException {
    myY += 10;
}

public void time() {
}
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
asdfs
  • 1

3 Answers3

0

Try this:

try{

   Thread.sleep(1000);

}catch(InterruptedException e) {

}
Guilherme
  • 456
  • 4
  • 12
  • Not a good idea if you want to do more than that as it freezes the whole program for 1 second (or longer!) – kleopi May 29 '19 at 15:56
  • Thanks! Now the time is working but it is not shifting up and down? How would I address this problem? – asdfs May 29 '19 at 16:57
  • Your render structure is wrong. You need to separate the render thread and the input thread. In one thread you put your event processing(key event) and in the other you draw the graphics. So you can control the FPS as you like. – Guilherme May 30 '19 at 20:50
0
TimerTask task = new TimerTask()
{
   @Override
            public void run()
            {
                time();//executed each second
            }
}
timer.schedule(TimerTask task,1000,1000)

That should help

kleopi
  • 460
  • 3
  • 13
0

Welcome to SO! Try using the schedule in Timer, like this:

Timer timer = new Timer();
timer.schedule(new YourClass(), 0, 1000);

Also, here's a great answer on the same issue: https://stackoverflow.com/a/12908477/10713658