1

I have a JFrame called gameFrame and I added a Jpanel called introPanel to it, gameFrame.add(introPanel) and I wanted to listen to the JPanel with a keylistener so I added one. When the user presses Enter, I removed the JPanel from the gameFrame and added the MainMenu theoretically, however the program doesnt listen to my keys. So i looked online and through SO and found out that I had to make the panel focusable so I did:

public IntroMenuStart() {
        this.addKeyListener(this);

        this.setFocusable(true);
        this.requestFocusInWindow();
}

However this did not work either. What else can I do to fix this?

Each Panel is a seperate class and they all get removed from gameframe and the next panel is added.

I would prefer to do this with keylistener.

EDIT

I fixed it by including this in my code for anyone wanting to know but I'm going to be changing my code to Keybindings like the 2 answers suggsted.

public void addNotify() {
    super.addNotify();
    requestFocus();
}
4

2 回答 2

4

i want to listne to the panel with a key listener so i add one. When the user presses Enter, i remove to JPanel form the gameFrame and add MainMenu, theoretically, however the program doesnt listen to my keys

If you search in deep in SO , you'll see that you have to use KeyBindings KeyListener has 2 greate issues, you listen to all keys and you have to have focus. Instead KeyBinding you bind for a key and you don't have to be in focus.

Simple Example:

AbstractAction escapeAction = new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
         //code here example
         ((JComponent)e.getSource()).setVisible(Boolean.FALSE);
    }};
 String key = "ESCAPE";
 KeyStroke keyStroke = KeyStroke.getKeyStroke(key);
 component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, key);
 component.getActionMap().put(key, escapeAction);

You can use these JComponent constants

    WHEN_ANCESTOR_OF_FOCUSED_COMPONENT 
    WHEN_FOCUSED 
    WHEN_IN_FOCUSED_WINDOW 
于 2013-07-24T23:03:43.643 回答
2

I believe that JPanel is not focuseable. Instead, use the key bindings.

于 2013-07-24T22:30:52.447 回答