假设我们开发的新插件的Perspective包含了两个part: 一个Editor,它包含了一个TableViewer , 再有一个View,它包含了一个Canvas
现在我们要模拟的场景是:用户点击了Editor上的Table里的rows, View会收到事件,Canvas会做出相应.同时,用户在Canvas上滑动鼠标,Editor会收到时间,Table会做出相应
场景1 : User --1--> TableViewer--2-->TableEditor--3-->CanvasView--4-->Canvas
场景 2: User-->Canvas-->CanvasView-->TableEditor-->TableViewer
但是Editor和View都是相对独立的Part,他们不需要知道彼此,那么如何完成交互呢?需要SelectionService的帮助
我们先研究场景1:
在这个场景中,是一个一环套一环的过程,用户的鼠标事件,沿着这条Path一直穿到Canvas
User --1--> TableViewer : 首先Tableviewer是一个Listener, 监听用户的鼠标事件,TableViewer已经实现了这部分的功能,因此这条路已经通了。继续
TableViewer--2-->TableEditor : 此地,TableViewer扮演selection provider, 而TableEditor是我们自己实现的新类,需要去监听TableViewer的事件 它可以自己去做Listener,也可以新添加一个Listener
所以在TableEditor的代码中
viewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
StructuredSelection selection = (StructuredSelection)event.getSelection();
System.out.println(selection.getFirstElement());
}
});
我们需要实作listener中的.selectionChanged()代码,完成接收到次事件后做什么, 我们需要它做什么呢,就是将这个事件继续发出去,能够让TableEditor获知想要知道是什么view或是editor被选择,要使用IPartService
If a dialog opens on top of the workbench window, the active part does not change, even though the active part loses focus.
The part service will also notify you when parts are closed, hidden, brought to the top of a stack, and during other lifecycle events.
Two types of listeners can be added to the part service: IPartListener and the poorly named IPartListener2.
You should always use this second one as it can handle part-change events on parts that have not yet been created because they are hidden in a stack behind another part. This listener will also tell you when a part is made visible or hidden or when an editor's input is changed:
使用ISelectionService,你可以添加一个Listener到Service中去跟踪active的part或者做简单查询。注意:一个part是active的,并不等价于它有focus。如果一个对话