-1

When I am using JFrame and I have a JPanel and some other component (like a JButton), I assign the wasd keys to the JFrame(KeyEvent), but the JPanel doesn't respond when I press a key.

Only when the JPanel is the only component in the JFrame will the JPanel respond to Key Events. How can I change this focus so that the JFrame sends Key Events to the JPanel.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366

1 Answers1

2

As with all questions relating to KeyListener not working, use the Key Bindings API, it will solve the focus related issues of KeyListener

Any suggestions to use requestFocusInWindow are hacks and will cause you more issues then they solve. Use the Key Bindings API, it was designed to help solve this issue

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • [How to Use Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) – MadProgrammer Jan 12 '16 at 03:51
  • I am just having a hard enough time drawing graphics as it is anyways. I see these people make cool java games with graphics and they make it look so much easier than actually is for me to do it. I am so frustrated with how to make the basic fundamentals of a simple graphics game. It is this barrier that has slowed me down for almost a year now. I don't know what to do! D: This is the best thing I've made: https://www.dropbox.com/sh/v6tacqvth1js5yj/AABDmGHnwCkSF8ipy0pIsIDta?dl=0 –  Jan 12 '16 at 04:04
  • Painting and graphics is complex, making games, even more so, so don't discourage if you don't succeed when you first get started – MadProgrammer Jan 12 '16 at 04:09
  • I don't even know where to start. Right now I am trying to make a package to handle different shapes and make them move around in a JPanel area. I sometimes just want to give up on it and learn Unity or Unreal. I feel like I am doing more work than I have to. Could we maybe move this discussion to the Java chat? (fish and chips) –  Jan 12 '16 at 04:13
  • For [example](http://stackoverflow.com/questions/33664601/draw-two-line-by-keytyped-event-in-java/33664850#33664850), [example](http://stackoverflow.com/questions/24522458/flipping-rotations-and-images/24523176#24523176), [example](http://stackoverflow.com/questions/34146965/java-swing-key-input-with-jpanel-added-to-joptionpane/34147249#34147249), [example](http://stackoverflow.com/questions/16622630/gradually-speeding-a-sprite/16623202#16623202) – MadProgrammer Jan 12 '16 at 04:13