Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

Instead of using a keylistener, can I use an "if" statement?

+2 votes
Instead of applying a keylistener to move my graphics object vertically using the UP and DOWN arrow keys, could I add an “if” statement that says something like “if the user presses “w”, then move the graphics object up 1 pixel or if the user presses “S”, then move the graphics object down 1 pixel? Is this plausible?
asked Feb 8, 2015 in (Winter 14) by Troy Barger (100 points)

1 Answer

+1 vote

Yes, you'd want to:

a) wait until the user has pressed a key (with a while loop that sleeps)

b) find out what key they pressed, and respond accordingly.

Something like this:

while (!panel.hasKeyboardInput()) {
   panel.sleep(10);
}

String keyPressed = panel.getKeyboardInput();

if (keyPressed.equals("w")) {
   //...
}

 

answered Feb 10, 2015 by Forrest Stonedahl (100 points)
...