为了让用户在WorkbenchPart(如IEditorPart)的Viewer(如TableViewer)里选择一个对象时,属性视图里能显示这个元素的属性,一般会将这个Viewer设置为该WorkbenchPart的site的selectionProvider:
editPart.getSite().setSelectionProvider(theViewer); |
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”一节。