7 Sept 2012

keylistener in java


KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher (new MyDispatcher());

You then need to create a key event dispatcher, and add your code into it
   private class MyDispatcher implements KeyEventDispatcher
    {
        @Override
        public boolean dispatchKeyEvent(KeyEvent e)
        {
            if (e.getKeyCode() == 38) //up key
            {
            //Do something when the up key is pressed
            System.out.println("The up key was pressed");
            }
            else if (e.getKeyCode() == 40) //down key
            {
                //Do something when the down key is pressed
                System.out.println("The down key was pressed");
            }
            return false;
        }
    }

0 comments:

Post a Comment