How does addNotify() and requestFocus() work in Java with JPanel?

addNotify() gets called whenever the Component gets added to a Container. This method can therefore be used to gain parent information without the risk of having a null parent, which in the constructor is more than likely.

requestFocus() makes a request that the given Component gets set to a focused state. This method requires that the component is displayable, focusable, visible and have all it’s ancestors be visible too. It is best to call requestFocusInWindow(), as that method is not platform dependent.

In the code example, your JPanel sends a request to be focused. This is useful, since the implementation of a KeyLisener, which would require the panel to be in a focused state. With the addNotify(), it just adds the listeners. This will hopefully only be called once, although no guarantee is made in this code example.

Leave a Comment