I’m using Key Events over Key Binding because I don’t understand key binding yet.
I make a JFrame with a JPanel with a Jbutton.
I instance the JPanel as panel in the frame’s class and the JButton as button in the panel’s class. I continue editing the panel’s class.
If I addKeyListener with a new keyAdapter that just prints “key pressed”, nothing happens if I type anything. BUT if I do button.addKeyListener with the same generic keyAdapter, “key pressed” will print when I push a key.
I assume this has something to do with instances. So my first question is: How can I have a component add a key listener to itself and/or why doesn’t calling the addKeyListener or even this.addKeyListener do this?
When I add a key listener the code keeps going (as it probably should) so I tried doing while(some boolean) thread.sleep(1000) just having the key listener change the boolean when a key is pressed. I simply want my code to wait until a key is pressed. I understand this isn’t much to go on but my question is: is there a better or cleaner way to pause methods/wait for input?
Probably because the comonent doesn’t have focus. KeyEvents are only dispatched to the component with focus. This is not a problem with Key Bindings because they can handle events even when the component doesn’t have focus.