<span style="font-size:18px;">1、</span>
public class AddContactAction extends Action implements
ISelectionListener,ActionFactory.IWorkbenchAction {
private final IWorkbenchWindow window;
public static String ID = "com.eclipsercp.hyperbola.addContact";
private IStructuredSelection selection;
public AddContactAction(IWorkbenchWindow window){
this.window = window;
setId(ID);
setText("&Add Contact...");
setToolTipText("Add a Contact to your Contacts list.");
setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
"com.eclipsercp.hyperbola", IImageKeys.ADD_CONTACT));
window.getSelectionService().addSelectionListener(this);
}
public void dispose(){
window.getSelectionService().removeSelectionListener(this);
}
@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
}
}
<span style="font-size:18px;">这是添加联系人的action,其中ID有两个作用,首先能够唯一标识一个action,其次在<span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 18px; line-height: 26px;">ApplicationActionBarAdvisor的<span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 18px; line-height: 26px;"> fillMenuBar()方法进行注册action时会用到这个ID。</span></span></span>
<span style="font-size:18px;"><span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 18px; line-height: 26px;"><span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 18px; line-height: 26px;">2、action会注册到selection listener中,可以看到AddContactAction是实现了ISelectionListener接口的,当treeviewer中的元素被选中时,selectionChanged()方法就会通知对应的action:</span></span></span>
<span style="font-size:18px;"><span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 18px; line-height: 26px;"><span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 18px; line-height: 26px;"></span></span></span><pre name="code" class="java">@Override
public void selectionChanged(IWorkbenchPart part, ISelection incoming) {
//selection containing elements
if(incoming instanceof IStructuredSelection){
selection = (IStructuredSelection)incoming;
setEnabled(selection.size() == 1 &&
selection.getFirstElement()instanceof ContactsGroup);
}else {
//other selections(containing text or other kinds)
setEnabled(false);
}
}