原程序:Snippet202
public class Snippet202 {
public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout (new FillLayout());
final Tree tree = new Tree(shell, SWT.VIRTUAL | SWT.BORDER);
// 生成节点的总是
final int[] iArr = new int[1];
tree.addListener(SWT.SetData, new Listener() {
public void handleEvent(Event event) {
System.out.println("Create the "+(++iArr[0]) +" item.");
TreeItem item = (TreeItem)event.item;
TreeItem parentItem = item.getParentItem();
String text = null;
if (parentItem == null) {
text = "node "+tree.indexOf(item);
} else {
text = parentItem.getText()+" - "+parentItem.indexOf(item);
}
item.setText(text);
// 设置可以接受几个子节点
item.setItemCount(3);
}
});
// 自动生成几个根节点
tree.setItemCount(5);
shell.setSize(400, 300);
shell.open();
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}
注意点:
1,Tree必须设置为SWT.VIRTUAL
2,必须处理SWT.SetData事件
3,tree.setItemCount(5);和item.setItemCount(3);
javadoc中对于SWT.VIRTUAL的解释是
TreeItems are to be populated by the client on an on-demand basis instead of up-front.
on-demand 一经要求、请求
up-front 在一开始
就是SWT.VIRTUAL树就是个虚的树,在得到用户、客户要求或者请求的时候才建立树的Item,而这些Item要设置有多少个子Item。