开发时总会用到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,这些都需要自己去调用相关处理方法。