Search code examples
javaswingawtkeylistenerjcomponent

For what component should I add KeyListener?


I have a GUI.

This GUI class extends JFrame.

In top of the screen there is a JLabel with some text.

In the center of the screen there is a JPanel, and n x n JButtons were added to this JPanel.

I need a KeyListener to react if I press a key.

For what component (JFrame, JLabel, JPanel, JButtons) should I add the KeyListener to work my program normally?


Solution

  • For what component should I add KeyListener?

    • you can to use Keylistener for (is designated)

      1. prehistoric AWT Component (Swing based on AWT)

      2. for more than 3 keyPressed in the same time or to determine the order

      3. but then is for Swing JComponents better to use KeyEventDispatcher or AWTEventListener (both react to singnals from keyboard)

    • otherwise use KeyBindings (e.g. Swing JComponents uses KeyBindings internally)