Abu Dhabi
Abu Dhabi

Reputation: 331

How to make a KeyListener trigger for all components of a JFrame?

I have a class, like so:

public class MyFrame extends javax.swing.JFrame implements KeyListener { ... }

In the constructor:

addKeyListener(this);
setFocusable(true);

This works as long as the window itself is in focus. If I focus on a component within that window, the key listener no longer listens. I want it so that whenever the window is the active window, but regardless on which specific sub-component the focus is on, the key listener will be triggered. I wish to keep focus traversal keys, for quality of life, but they're not critical.

How do I do this?

Upvotes: 0

Views: 2104

Answers (2)

Muhammad Hamed
Muhammad Hamed

Reputation: 1239

Add the KeyListener recursively to the sub components.

Check this

How to get all elements inside a JFrame?

i hope this could help!

Upvotes: 2

MadProgrammer
MadProgrammer

Reputation: 347332

Preferably you would use the key bindings API for each component, you can use the key bindings to change the level of focus required to trigger the given action, for example, for when the component has focus, when the component is a child of a focused component or when it is contained within the focused window...

See How to Use Key Bindings for more details

Upvotes: 3

Related Questions