0

Here is a simplified version of my code

public class StateController extends GraphicsProgram {

    public Menu menu = new Menu();

    public void run() {
        addMouseListeners();
        addKeyListeners();
    }

}

public class Menu {
    int x = 0;

    public void keyPressed(KeyEvent e) {
       System.out.println(x);
    }

    public void mousePressed(MousEvent e) {
       System.out.println(x);
    }

}

The program detects when the mouse is pressed, but it does not print X when a key is. Can you see any problems?

Thank very much.

2
  • 1
    Please, post a short but complete example of what you are doing. The code you posted makes no sense, so it's impossible for us to tell you what is wrong.
    – BackSlash
    Dec 16, 2014 at 15:54
  • Here is a simplified version of my code - a simplified version doesn't really help us. The problem may be in the code you decided not to include. Post a proper SSCCE that demonstrates the problem.
    – camickr
    Dec 16, 2014 at 16:09

2 Answers 2

1

Assuming your code actually compiles and you implemented the KeyListener interface correctly, KeyEvents are only dispatched to components that have focus. Your StateController doesn't have focus.

By default a JPanel is not focusable. So I'm guessing your StateController class is extending JPanel. So you need to:

  1. Make the panel focusable by using setFocusable(true) in the constructor of your class
  2. Invoke panel.requestFocusInWindow() AFTER the GUI has been made visible. You can only request focus on a component in a visible GUI.
1

If you add listeners to your class, this class has to implement the listener interfaces in order to get the notifications:

public class StateController extends GraphicsProgram implements MouseListener, KeyListener

Or you do it on-the-fly:

yourUiElement.addKeyListener(new KeyListener() {
        public void keyTyped(KeyEvent e) {}         
        public void keyReleased(KeyEvent e) {}          
        public void keyPressed(KeyEvent e) {
            System.out.println(x);
        }
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.