1

I created a simple Nibbles (Snakes) game and everything works perfectly.

However, when I copy everything over to my mac (develop on a PC) and compile the same java files, the keyAdapter event listener for moving my snake around doesn't respond.

I'm not sure what is wrong.

here's the snippet, but if anyone would be willing to take a look at the whole program, I could send that privately. THANKS!

getThis().addKeyListener(new KeyAdapter()  {
        public void keyPressed(KeyEvent event) {                    
            if(event.getKeyCode() == KeyEvent.VK_UP)
                if(!glass.game.getDirection().equals("D"))
                    glass.game.setDirection("U");

            if(event.getKeyCode() == KeyEvent.VK_DOWN)
                if(!glass.game.getDirection().equals("U"))
                    glass.game.setDirection("D");

            if(event.getKeyCode() == KeyEvent.VK_LEFT)
                if(!glass.game.getDirection().equals("R"))
                    glass.game.setDirection("L");

            if(event.getKeyCode() == KeyEvent.VK_RIGHT)
                if(!glass.game.getDirection().equals("L"))
                    glass.game.setDirection("R");
          }
});   
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
Wangagat
  • 95
  • 4
  • 11
  • 2
    General advice: Use Enums for directions, not strings. – Kiril Kirilov Apr 02 '12 at 08:40
  • 1
    "To fire keyboard events, a component must have the keyboard focus."—[*How to Write a Key Listener*](http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html). – trashgod Apr 02 '12 at 08:58

1 Answers1

6

use KeyBindings instead of KeyListener, KeyListener isn't designated for listening KeyEvents in the Swing JComponents, this's listener for AWT Components, example here

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319