Search code examples
javaoopkeyevent

Does object oriented programming work with 2 methods?


I have encountered a problem while writing code for a small game I've been working on. In the following code I am trying to use object oriented programming. as I am using KeyEvent I think I need to use 2 methods however for some reason int key cannot be found. Can somebody help me?

    class KeyEvt {
        void keyPressed (KeyEvent e) 
        {
            int key = e.getKeyCode();
        }
    }
    class Dodger {
        public static void main (String args[])

        {
            boolean GameOver = false;
            int obst;
            KeyEvt left = new KeyEvt();

            do
            {
                obst = (int) (Math.random() * 4) +1;
                if (obst == 1)
                {
                    System.out.println("   ---");
                    if (KeyEvt.key == KeyEvent.VK_LEFT){}
                }

Solution

  • In your class KeyEvt you don't declare an instance variable key, but a method variable key in keyPressed. This method variable will 'disapear' as soon as the method has finished.

    In order to retain the value after the method has completed you need to declare it as an instance variable:

    class KeyEvt {
        public int key;
        void keyPressed (KeyEvent e) 
        {
            key = e.getKeyCode();
        }
    }
    

    You'd also need to access an instance of the KeyEvt class, not the KeyEvt class itself:

    if (left.key == KeyEvent.VK_LEFT){}
    

    Obviously this lacks a lot of encapsulation (key is modifiable by others), and as the original KeyEvent already has the keycode the question arises why you'd need a KeyEvt class after all as the the KeyEvent class provides what you need.