2

I am trying to move a stick figure up and down in a JFrame. When I change the y it the whole thing moves. But I want it to move up, wait a second, then move down. Thread.sleep has not been working. comp is a object of a class draws the stick figure.

if(key == KeyEvent.VK_UP)
{
    comp.setY(y++);
    comp.setY(y--);
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
Jacob
  • 425
  • 3
  • 13
  • if(key == KeyEvent.VK_UP) { comp.setY(y++); frame.invalidate(); frame.validate(); frame.repaint(); try { Thread.sleep(1000); } catch (InterruptedException e) { } comp.setY(y--); } – Jacob Jan 28 '15 at 22:31
  • or this if(key == KeyEvent.VK_UP) { comp.setY(y++); SwingUtilities.updateComponentTreeUI(frame); try { Thread.sleep(1000); } catch (InterruptedException e) { } comp.setY(y--); } – Jacob Jan 28 '15 at 22:31
  • Neither of these work. and sorry for so many comments, every time I tried to do a new line I accidentally commented. – Jacob Jan 28 '15 at 22:32

1 Answers1

1

Swing is a single threaded environment, it's also, reasonably optimised for what it does.

It's possible that the repaint manager is condensing the repaint requests down into a single request, so you only see the last request.

See Concurrency in Swing for more details.

What you "can" do, is postpone the second update, using something like a Swing Timer...

Something like...

if(key == KeyEvent.VK_UP)
{
    comp.setY(y++);
    // You may need to force a repaint here
    Timer timer = new Timer(1000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            comp.setY(y--);
            // You may need to force a repaint here
        }
    });
    timer.setRepeats(false);
    timer.start();
}

...for example.

See How to use Swing Timers for more details.

Personally, I would setup a Timer which was capable of performing both the up and down movement based on a state variable it carries, but that's me

I would also discourage the use KeyListeners as they are just more trouble than they are worth, and instead would encourage the use of the Key Bindings API, see How to Use Key Bindings for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366