1

Basically i have created a key listener connected to my JPanel.. And sometimes when i compile and run it it does work realy good and no problems what so ever.. But then sometimes when i compile it wont work. It doesn't recognise keypresses.

Here is the code i used for key listener in my JPanels update method:        

if(keyListener.getMovingRight() == KeyEvent.VK_RIGHT){
            player.playerMoveRight();
        }
        if(keyListener.getMovingLeft() == KeyEvent.VK_LEFT){
            player.playerMoveLeft();
        }
        if(keyListener.getMovingUp() == KeyEvent.VK_UP){
            player.playerMoveUp();
        }
        if(keyListener.getMovingDown() == KeyEvent.VK_DOWN){
            player.playerMoveDown();
        }

And the above code knows if keys was pressed from this class:

public class KeyBoard implements KeyListener {

    private int playerMoveUp;
    private int playerMoveDown;
    private int playerMoveLeft;
    private int playerMoveRight;

    public KeyBoard(){
        playerMoveUp = 0;
        playerMoveDown = 0;
        playerMoveLeft = 0;
        playerMoveRight = 0;
    }

    @Override
    public void keyTyped(KeyEvent keyEvent) {
    }

    @Override
    public void keyPressed(KeyEvent keyEvent) {

        //Switch statement to get which keys were pressed
        switch(keyEvent.getKeyCode()){

            case KeyEvent.VK_UP:
                playerMoveUp = keyEvent.getKeyCode();
                break;

            case KeyEvent.VK_DOWN:
                playerMoveDown = keyEvent.getKeyCode();
                break;

            case KeyEvent.VK_LEFT:
                playerMoveLeft = keyEvent.getKeyCode();
                break;

            case KeyEvent.VK_RIGHT:
                playerMoveRight = keyEvent.getKeyCode();
                break;
        }
    }

    @Override
    public void keyReleased(KeyEvent keyEvent) {

        //Switch statement to get which keys were released
        switch(keyEvent.getKeyCode()){

            case KeyEvent.VK_UP:
                playerMoveUp = 0;
                break;

            case KeyEvent.VK_DOWN:
                playerMoveDown = 0;
                break;

            case KeyEvent.VK_LEFT:
                playerMoveLeft = 0;
                break;

            case KeyEvent.VK_RIGHT:
                playerMoveRight = 0;
                break;
        }
    }

    public int getMovingUp(){
        return playerMoveUp;
    }
    public int getMovingDown(){
        return playerMoveDown;
    }
    public int getMovingLeft(){
        return playerMoveLeft;
    }
    public int getMovingRight(){
        return playerMoveRight;
    }
}

And i ofcourse added the key listener to the JPanel by doing this:

panel.addKeyListener(KeyBoardClasshere);

Since it wasnt working regularly i tried something else called Key Bindigs since i heard that would increase my chances..

I added this in my JPanel class and commented out the key listener in the update method:

   

public void keyBindingsInitialize(ActionMap am, InputMap im){
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "Right");
        am.put("Right", RightBind);

        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "Left");
        am.put("Left", LeftBind);

        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "Up");
        am.put("Up", UpBind);

        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "Down");
        am.put("Down", DownBind);
    }
    
    Action RightBind = new AbstractAction(){
        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            player.playerMoveRight();
        }
    };
    Action LeftBind = new AbstractAction(){
        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            player.playerMoveLeft();
        }
    };
    Action UpBind = new AbstractAction(){
        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            player.playerMoveUp();
        }
    };
    Action DownBind = new AbstractAction(){
        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            player.playerMoveDown();
        }
    };

This also works but sometimes when i compile and run the project it just doesnt work and then it works if i terminate the project and then run it again.. Its soo strange in my oppinion.. Anyone have suggestions?

EDIT: I followed the answear on this question:KeyListener on JPanel randomly unresponsive

I do get response from clicking the button that apears and the spacebar but not the keys that is used in the update method.. And now after i added the button sometimes when i run the application all i get is a grey window and have to restart it a couple of times to make it normal again just as in the question i linked.

Community
  • 1
  • 1
User
  • 1,458
  • 3
  • 16
  • 40
  • Have you tried adding your KeyListener to your frame instead of your panel? Not sure if that'll work but it's worth a try – nullptr May 03 '13 at 20:41
  • 1
    You are seeing a strange error that doesn't occur with each run of the program but only occurs intermittently. This suggests to me that you may have a Swing threading issue, that somewhere, somehow your code may not be obeying Swing threading rules appropriately. Are you taking care to start your GUI on the EDT, the Swing Event Dispatch Thread? Can you create and post an [sscce](http://sscce.org) that demonstrates your problem? – Hovercraft Full Of Eels May 03 '13 at 20:41
  • @nullptr: I have strong doubts about your recommendation. – Hovercraft Full Of Eels May 03 '13 at 20:42
  • @HovercraftFullOfEels im not sure i can create an SSCCE since this is a big application with realy many classes.. No im not starting my GUI on an Event Dispatch Thread – User May 03 '13 at 20:45
  • 1
    Then, yes, please do start it on the EDT and see if that helps. You've nothing to lose in this. – Hovercraft Full Of Eels May 03 '13 at 20:48
  • @nullptr That did not work, Sorry – User May 03 '13 at 20:48
  • @HovercraftFullOfEels It make whole my application stop working :/ – User May 03 '13 at 20:54
  • Following the answear on this question i do get a response when i click space or the button but the other keys do still not respond: http://stackoverflow.com/questions/8087536/keylistener-on-jpanel-randomly-unresponsive – User May 03 '13 at 21:06
  • @Rakso: then I definitely fear that you have some threading issues going on. – Hovercraft Full Of Eels May 03 '13 at 21:12
  • @HovercraftFullOfEels Could you send me a solution or a possible solution or something that i can read up about so i get more knowledged about theese threading issues? – User May 03 '13 at 21:14
  • 1
    @Rakso: if it were only that simple, quick and easy, I would, but the solution will mean going through your code and making sure that all Swing-related calls are made on the EDT and all longer-running non-Swing calls in a background thread, and so the solution will of necessity be completely dependent on the structure of your program. As a first test, you'd best again try to start your GUI on the EDT and then tweak it until it runs. – Hovercraft Full Of Eels May 03 '13 at 21:21
  • 1
    To catch EDT violations, try one the approaches cited in this [Q&A](http://stackoverflow.com/q/7787998/230513). – trashgod May 03 '13 at 21:21

2 Answers2

1

Try adding

setFocusable(true);

to your JPanel's constructor.

Michał Tabor
  • 2,441
  • 5
  • 23
  • 30
0

Solved it by adding frame.revalidate(); in my game loop. Thanks for all answears!

User
  • 1,458
  • 3
  • 16
  • 40
  • @HovercraftFullOfEels Well after adding this it did start working correctly – User May 03 '13 at 21:51
  • 3
    I'm not doubting that, but it smells like a kludge that is hiding a larger more pernicious problem, mainly a kludge to hide a threading issue. If I'm right, then we'll surely see you again for another problem that occurs intermittently with your GUI. I hope I'm wrong though. – Hovercraft Full Of Eels May 03 '13 at 21:55