Jump to content

Keyboard loosing focus

- - - - -

  • Please log in to reply
3 replies to this topic

#1
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts
Well I don't know if it's the right way to say what's happening with my Space Invaders clone.
The problem is that if for example you minimize the game and reopen it, or if its window "looses focus" for a second, keyboard commands don't work anymore.

I implemented the commands like this:

public class GFrame extends JFrame {

        ...

        ...


	protected void processKeyEvent(KeyEvent e){

		int keyCode = e.getKeyCode();

		int keyId = e.getID();

		

		if(keyCode == KeyEvent.VK_X && keyId == KeyEvent.KEY_PRESSED){

			//do something

		}

		else if(keyId == KeyEvent.KEY_PRESSED){

			//do something

		} else if(keyId == KeyEvent.KEY_RELEASED){

			if(keyCode == KeyEvent.VK_LEFT && playerShip.move==PlayerShip.MOVE_LEFT){

				//do something

			}

			if(keyCode == KeyEvent.VK_RIGHT && playerShip.move==PlayerShip.MOVE_RIGHT){

				//do something

			}

		}

		

		if(keyCode == KeyEvent.VK_P && keyId == KeyEvent.KEY_PRESSED){

			//do something

		}

		

		if(keyCode == KeyEvent.VK_S && keyId == KeyEvent.KEY_PRESSED){

			//do something

		}

		

		//others here..

	}

}

I know it's messy, I'll fix that but I don't think that's the problem here.
Any suggestions?

#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
--Assuming you added the keyListener to the JFrame.--
Maybe if you reopen the frame, the JPanel inside gets focus, and not the frame? Maybe try adding a focuslistener on the JPanel inside it, and if it receives focus do JFrame.requestFocus();

#3
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts
requestFocus() seems to work =)

#4
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts
Well, no, keyboard input stops working as soon as I click on the canvas

edit: solved by calling parentWindow.requestFocus() after a mouse click




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users