Reputation:
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.
Upvotes: 0
Views: 232
Reputation: 347214
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
KeyListener
will only respond to key events when the component it is registered to:
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
Upvotes: 1