问题
I have not got a clear idea how does super.addNotify()
and requestFocus()
methods of JPanel
work in general and within the code below in particular:
public class Panel extends JPanel
implements keyListener, MouseListener, MouseMotionListener {
public Panel() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setFocusable(true);
requestFocus();
}
public void addNotify() {
super.addNotify();
if (thread == null) {
addKeyListener(this);
addMouseListener(this);
addMouseMotionListener(this);
thread = new Thread(this);
thread.start();
}
}
// Some unrelated code follows
}
Could someone please explain it to me?
回答1:
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.
回答2:
Have a look at this for the proper explanation of addNotify(): What is addNotify();?
As for requestFocus(), this method is used to make the component get input focus. This means that if you press any kind of key or give any input, the input is heard by the respective Listener for that component.
Thus, in the code mentioned by you, it is logical for the panel to request focus in the constructor during its initialization, so that any kind of input on it can be registered to its specified event listeners.
来源:https://stackoverflow.com/questions/22386477/how-does-addnotify-and-requestfocus-work-in-java-with-jpanel