In order for KeyListener
to work, the component it is registered to MUST be focusable AND have keyboard focus. Most containers like JComponent
and JPanel
aren't focusable by default (and I'd be VERY careful before considering making them so). This means that the moment you add a component which can accept keyboard focus (and it receives keyboard focus), your KeyListener
will no longer work.
This is one of the many reasons we recommend against using it. Instead, make use of the Key Bindings API, which allows you to, among other things, determine the level of focus a component will need in order to trigger the bindings
See How to Use Key Bindings for more details
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…