Adding Controls to the Toolbar

Another common feature is to place SWT controls in the toolbar instead of just buttons. Again, the key here is to put an IContributionItem into the toolbar instead of an IAction. This works because ToolItems and CoolItems both allow controls to be set as their contents. JFace includes a helper class, ControlContribution, that supports adding controls to toolbars and coolbars. The code for ControlContribution is shown below:

org.eclipse.jface/ControlContribution
public abstract class ControlContribution {
  protected abstract Control createControl(Composite parent);

  public final void fill(Composite parent) {
    createControl(parent);
  }

  public final void fill(Menu parent, int index) {
    Assert.isTrue(false, "Can't add a control to a menu");
  }

  public final void fill(ToolBar parent, int index) {
    Control control = createControl(parent);
    ToolItem item = new ToolItem(parent, SWT.SEPARATOR, index);
    item.setControl(control);
    item.setWidth(computeWidth(control));
  }
} 

To add your own control, subclass ControlContribution and implement createControl(Composite) to return the desired control. The returned control is added to the toolbar by placing it in a dedicated tool item. The following snippet from Hyperbola's ActionBarAdvisor shows how to place a ComboBox into the Hyperbola main toolbar:

org.eclipsercp.hyperbola/ApplicationActionBarAdvis
protected void fillCoolBar(ICoolBarManager coolBar) {
  IToolBarManager toolbar = new ToolBarManager(coolBar.getStyle());
  coolBar.add(toolbar);

  IContributionItem comboCI = new ControlContribution() {
    protected Control createControl(Composite parent) {
      Combo c = new Combo(parent, SWT.READ_ONLY);
      c.add("one");
      c.add("two");
      c.add("three");
      return c;
    }
  };
  toolbar.add(comboCI);
} 

你可能感兴趣的:(Adding Controls to the Toolbar)