除了讲述什么组件可以在ZUML页面被创建外,开发人员可以手动创建组件。所有的组件都是具体的(concrete),你可以直接[15]通过它们的构造函数(constructors)来创建它们。
<window id="main">
<button label="Add Item">
<attribute name="onClick">
new Label("Added at "+new Date()).setParent(main);
new Separator().setParent(main);
</attribute>
</button>
<separator bar="true"/>
</window>
当一个组件被手动创建时,它并没有自动被加到页面。换句话说,它并不在用户的浏览器中出现。为了将它加到页面,你可以调用setParent,appendChild或 insertBefore方法来为其指定一个父类(parent),如果父类组件是页面的一部分,那么它也变成了页面的一部分。
组件类并没有destroy 或close方法[16],当一个组件从页面中被拆卸的时候就会从浏览器中内移除。它表现的就像附着在页面上一样。
<window id="main">
<zscript>Component detached = null;</zscript>
<button id="btn" label="Detach">
<attribute name="onClick">
if(detached != null) {
detached.setParent(main);
detached = null;
btn.label = "Detach";
} else {
(detached = target).setParent(null);
btn.label = "Attach";
}
</attribute>
</button>
<separator bar="true"/>
<label id="target" value="You see this if it is attached."/>
</window>
在上面的例子中,你可以用setVisible方法来产生类似的效果。但是setVisible(false)方法并没有把组件从浏览器中移除,它只是使一个组件(及其所有的子组件(children))变得不可见。
当一个组件从页面被卸载后,如果应用程序没有涉及到该组件,它所占用的内存会被Java虚拟机的垃圾回收机制(JVM's garbage collector)所释放。
对于根本不习惯使用ZUML的开发人员来说,他们可以使用被称为richlet的方法来手动创建所有的组件。
import org.zkoss.zul.*;
public class TestRichlet extends org.zkoss.zk.ui.GenericRichlet {
public void service(Page page) {
page.setTitle("Richlet Test");
final Window w = new Window("Richlet Test", "normal", false);
new Label("Hello World!").setParent(w);
final Label l = new Label();
l.setParent(w);
//...
w.setPage(page);
}
}
请参考高级特性一章中Richlets一节。