Eclipse CheckboxTreeViewer节点选中状态的初始化

使用CheckboxTreeViewer控件时,要初始化已经选中的状态,代码如下


// Create the tree viewer to display the file tree
		tv = new CheckboxTreeViewer(composite);

		// When user checks a checkbox in the tree, check all its children
		tv.addCheckStateListener(new ICheckStateListener() {
			public void checkStateChanged(CheckStateChangedEvent event) {

				// If the item is checked . . .
				if (event.getChecked()) {

					// . . . check all its children
					tv.setSubtreeChecked(event.getElement(), true);
				}

			}
		});
		tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
		tv.setContentProvider(new FileTreeContentProvider());
		tv.setLabelProvider(new FileTreeLabelProvider());


对其做初始化操作:
IProjectDescription description = project.getDescription();

			String[] natures = description.getNatureIds();

			TreeItem[] list = tv.getTree().getItems();

			
			//已有构件呈选中状态
			for (TreeItem item : list) {
				
				Element element = (Element) item.getData();

				for (String nature : natures) {

					if (element.elementText("natureId").equals(nature)) {

						item.setChecked(true);

					}

				}

			}


关键代码是这一句:

Element element = (Element) item.getData();

这样可以取到节点的数据来源对象,而不用去根据某个属性遍历查找。

你可能感兴趣的:(java,eclipse)