问题描述
我还不清楚JPanel
的super.addNotify()
和requestFocus()
方法如何正常工作,尤其是在以下代码内如何工作:
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
}
有人可以向我解释吗?
推荐答案
addNotify()
.因此,可以使用此方法来获取父级信息,而不必具有null
父级的风险,而在构造函数中该父级的可能性更大.
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()
发出请求,将给定的Component
设置为聚焦状态.此方法要求组件是可显示的,可聚焦的,可见的,并且其所有祖先也都可见.最好调用requestFocusInWindow()
,因为该方法不依赖于平台.
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.
在代码示例中,您的JPanel
发送一个要关注的请求.这很有用,因为要实现KeyLisener
,这将要求面板处于聚焦状态.使用addNotify()
,它仅添加侦听器.尽管希望在此代码示例中没有保证,但这将希望仅被调用一次.
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.
这篇关于使用JPanel在Java中如何运行addNotify()和requestFocus()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!