Domanda

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?

È stato utile?

Soluzione 2

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)

Altri suggerimenti

The JFrame would be the smartest choice given that it is a top level ancestor you would be able to avoid focus problems. However, if you say you were to implement a JTextField it would then be necessary to add the keylistener to the JTextField because focus is drawn away from parallel components in order to consume the ability to type into the field.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top