<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);
}
}