为了让用户在WorkbenchPart(如IEditorPart)的Viewer(如TableViewer)里选择一个对象时,属性视图里能显示这个元素的属性,一般会将这个Viewer设置为该WorkbenchPart的site的selectionProvider:
editPart.getSite().setSelectionProvider(theViewer);
但如果是一个WorkbenchPart里有多个Viewer的情况呢?我们可以实现为当用户在任意一个Viewer里选择了一个对象后,属性视图里显示这个对象的属性。为此,根据黄老大的提示,需要写一个CompositeSelectionProvider,它实现ISelectionChangedListener以监听每个Viewer的选择事件,同时它要实现ISelectionProvider,因为我们要把它设置为该site的selectionProvider:
class CompositeSelectionProvider implements ISelectionProvider, ISelectionChangedListener {
ISelection selection;
List listeners = new ArrayList();
public void addSelectionChangedListener(ISelectionChangedListener listener) {
listeners.add(listener);
}
public ISelection getSelection() {
return selection;
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
listeners.remove(listener);
}
public void setSelection(ISelection selection) {
this.selection = selection;
final SelectionChangedEvent e = new SelectionChangedEvent(this, selection);
Object[] listenersArray = listeners.toArray();
for (int i = 0; i < listenersArray.length; i++) {
final ISelectionChangedListener l = (ISelectionChangedListener) listenersArray[i];
Platform.run(new SafeRunnable() {
public void run() {
l.selectionChanged(e);
}
});
}
}
/*****************************************************************
************** ISelectionChangedListener implementation **********
******************************************************************/
public void selectionChanged(SelectionChangedEvent event) {
setSelection(event.getSelection());
}
}
在WorkbenchPart#createPartControl()方法里让这个CompositeSelectionProvider监听每个viewer的选择事件,并把它设置为site的selectionProvider,代码如下:
//The composite selectionProvider instance
CompositeSelectionProvider compositeSelectionProvider=new CompositeSelectionProvider();
public void createPartControl(Composite parent) {
...
viewer1.addSelectionChangedListener(compositeSelectionProvider);
viewer2.addSelectionChangedListener(compositeSelectionProvider);
...
getSite().setSelectionProvider(compositeSelectionProvider);
}
注:在这篇教程里也有类似的解决方法,见“Multiple Selection Providers Within a Part”一节。
搬家前链接:https://www.cnblogs.com/bjzhanghao/archive/2006/10/23/537205.html
欢迎转载
请保留原始链接:https://bjzhanghao.com/p/2776
请保留原始链接:https://bjzhanghao.com/p/2776