0

I am in the process of refactoring a lot of code for our game to make the object-couplings as nonexistant as possible (for easier testing and future implementations). Currently my JFrame listens for keys, sends it to a eventmanager class, who again needs a reference to every object that performs an action on keyinput and calls a method on those objects.

It seems like a good idea to keep the responsiblity of responding to keyevents within the objects instead, this would for instance allow me to change the current screen and have the new screen behave differently without checking different global states (like switching to a gamemenu).

But I have no idea how to implement a keylistener for my custom objects, it seems it must be a swing/awt component. How would one add a KeyListener to a custom object? I know how to create custom events and custom listeners but don't know how to capture keyboard input via those methods.

arynaq
  • 6,710
  • 9
  • 44
  • 74

2 Answers2

2

Don't use KeyListener. Instead use Swing key bindings:

javax.swing.JComponent.registerKeyboardAction(ActionListener, KeyStroke, int)
javax.swing.JComponent.getInputMap(int)
javax.swing.JComponent.getActionMap()

Check out the tutorial: http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html

Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
1
  • this is reason for why is implemented KeyBindings

    1. most scallable abstraction (with or without hunting for Focus to the concrete JComponents)

    2. output could be Swing Action (the same abstraction, managable, scallable)

    3. the best of ways for Painting in Swing

    4. Swing used KeyBindings for internal commnads and short_cuts

  • another way is to use AWTEventListener (mouse & key events),

    1. but I'd be to use for compicated key_shortcuts

    2. more than three key are presses in same time

    3. detect sequence of chars

    4. for paitning in AWT by using OpenGL/CL

    5. special cases where KeyBindings, KeyListener or implemented notifiers in APIs aren't proper Listeners

  • my similair question how to add any Listener to Icon

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319