Jface TreeViewer 设置选中

    开发时总会用到JFace封装的各种Viewer,它们虽然很方便,但在一些特殊情境下就不一定好使,比如TreeViewer,假定要在初始化以后自动选中某个模型对应的节点。

   TreeViewer提供了一个API方法——setSelection(),用了感觉没什么效果,跟了一下发现在org.eclipse.jface.viewers.StructuredViewer .setSelection(ISelection selection, boolean reveal)中

	public void setSelection(ISelection selection, boolean reveal) {
		/**
		 * <p>
		 * If the new selection differs from the current selection the hook
		 * <code>updateSelection</code> is called.
		 * </p>
		 * <p>
		 * If <code>setSelection</code> is called from within
		 * <code>preserveSelection</code>, the call to
		 * <code>updateSelection</code> is delayed until the end of
		 * <code>preserveSelection</code>.
		 * </p>
		 * <p>
		 * Subclasses do not typically override this method, but implement
		 * <code>setSelectionToWidget</code> instead.
		 * </p>
		 */
		Control control = getControl();
		if (control == null || control.isDisposed()) {
			return;
		}
		if (!inChange) {
			setSelectionToWidget(selection, reveal);
			ISelection sel = getSelection(); //此处为null
			updateSelection(sel);
			firePostSelectionChanged(new SelectionChangedEvent(this, sel));
		} else {
			restoreSelection = false;
			setSelectionToWidget(selection, reveal);
		}
	}

 

ISelection sel = getSelection(); //此处为null

工作有点紧急,没有仔细跟踪,想着Tree本身有select()方法,绕一下先实现了再说。

 JFaeUtil类:

public class JFaceUtil {

	private JFaceUtil() {
	}

	/**
	 * Get the matching tree item.
	 * 
	 * Call {@link #getItemIndex(Tree, Object)}
	 * 
	 * @param tree
	 *            - Control
	 * @param obj
	 *            - the object data
	 * @return - if matching return the matching item, otherwise null.
	 */
	public static TreeItem getItem(Tree tree, Object obj) {
		int index = getItemIndex(tree, obj);
		if (index == -1) {
			return null;
		}
		return tree.getItem(index);
	}

	/**
	 * Get the matching tree item index.
	 * 
	 * @param tree
	 *            - Control
	 * @param obj
	 *            - the object data
	 * @return - if matching return the matching item index, otherwise -1.
	 */
	public static int getItemIndex(Tree tree, Object obj) {
		if (tree == null || obj == null) {
			return -1;
		}

		for (int index = 0; index < tree.getItemCount(); index++) {
			TreeItem item = tree.getItem(index);
			if (item.getData() == obj) {
				return index;
			}
		}
		return -1;
	}
}

 方法有点土,但还是实现了。不过这个选中不会触发TreeViewer的SelectionListener监听器,以及SelectionChangedListener,这些都需要自己去调用相关处理方法。

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值