您的位置:首页 > 大数据 > 人工智能

布局管理器中的两个方法validate()与layoutContainer()

2011-04-22 22:59 281 查看
今天在写swing程序时遇到下面两个方法,Container.validate()方法与LayoutManager.layoutContainer(Container parent)方法。不是太熟悉,查了一下API仍没有看太明白,就到网上查了一下,得到如下信息:
1、 layoutContainer是最重要的方法,因为组件的最终布局都是在该方法中实现的。这个方法会被awt-swing框架自动调用,例如改变组件的字体、容器尺寸改变等都会引起该方法的调用。
2、 java.awt.Container的validate方法实现代码:


Code:

public void validate()

{

/* Avoid grabbing lock unless really necessary. */

if (!isValid())

{

boolean updateCur = false;

synchronized (getTreeLock())

{

if (!isValid() && peer != null)

{

ContainerPeer p = null;

if (peer instanceof ContainerPeer)

{

p = (ContainerPeer) peer;

}

if (p != null)

{

p.beginValidate();

}

validateTree();

if (p != null)

{

p.endValidate();

updateCur = isVisible();

}

}

}

if (updateCur)

{

updateCursorImmediately();

}

}

}

注意该方法中调用了validateTree()[/b]方法,下面给出validateTree()[/b]方法实现代码:

Code:

protected void validateTree()

{

if (!isValid())

{

if (peer instanceof ContainerPeer)

{

((ContainerPeer)peer).beginLayout();

}

doLayout();

for (int i = 0; i < component.size(); i++)

{

Component comp = component.get(i);

if ((comp instanceof Container) && !(comp instanceof Window)

&& !comp.isValid())

{

((Container)comp).validateTree();

}

else

{

comp.validate();

}

}

if (peer instanceof ContainerPeer)

{

((ContainerPeer)peer).endLayout();

}

}

super.validate();

}

注意该方法中调用了doLayout()[/b]方法,下面给出doLayout()[/b]方法实现代码:

Code:

public void doLayout()

{

layout();

}

/**

* @deprecated As of JDK version 1.1,

* replaced by <code>doLayout()</code>.

*/

@Deprecated

public void layout()

{

LayoutManager layoutMgr = this.layoutMgr;

if (layoutMgr != null)

{

layoutMgr.layoutContainer(this);

}

}

在API文档中,关于此方法的用法有如下说明:使此容器布置其组件。大部分程序不应该直接调用此方法,而是应该调用[/b] [/b]
validate[/b]
[/b]方法。[/b]
至此,我已经明白了这两个方法之间的关系。通过这一过程,我又更加深刻地认识到一点:要想学好java,还要时刻记得学习源码!当然,互联网对我们的学习也是有很大帮助的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: