简体   繁体   中英

KeyListener always gives me an error when trying to add it to my JFrame

Every time I try to add my separate class that holds all of my key inputs to my JFrame, Eclipse tells me to do this: frame.add(frame, new KeyInput()); , which returns the error:

Exception in thread "main" java.lang.IllegalArgumentException: adding container's parent to itself

. I understand this error and where it came from:

frame.add(frame, new KeyInput());
          ^^^^^

, but if I take the frame component out, I get the error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The method add(Component) in the type Container is not applicable for the arguments (KeyInput)

This one I don't understand, but get the gist: Eclipse caught an actual error.

Assuming that KeyInput is an instance of a KeyListener , then you "should" be using addKeyListener defined in java.awt.Component (which javax.swing.JFrame inherits from)

This is further outlined in How to write key listeners

However, there are any number of issues which could result from doing this. Because you're adding the listener to the base frame, you're ignoring the fact that there are a number components between it and the user, all of which could consume the event or steal focus

为JRootPane

KeyListener will only respond to key events when the component it is registered to:

  • is focusable
  • and has keyboard focus

This means that other components which also respond to keyboard input can steal the keyboard focus and your listener will no longer be triggered. This is a very common issue with KeyListener which has been resolved through the Key bindings API

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM