Drop down menu from a toolbar button in JFace

January 19th, 2008

I have been programming in SWT/JFace for some time now.

Today I needed a toolbar button that would display a popup menu when clicking the arrow next to the button. There are snippets around that show how to do this using plain SWT. After some experimentation I found how to do it in JFace. Actually, it is pretty easy. The JFace action is created with the Action.AS_DROP_DOWN_MENU style, and all you have to do is set the menu creator using

    setMenuCreator (myMenuCreator);

myMenuCreator must be an instance of a class implementing the IMenuCreator interface.

My action, that should save the current file, giving the user the option to "save" or "save as..." in the popup menu, finally looked something like this:

JAVA:
  1. protected class SaveConfigurationAction
  2.     extends Action implements IMenuCreator
  3. {
  4.     protected MenuManager m_menu;
  5.  
  6.     public SaveConfigurationAction ()
  7.     {
  8.         super ("Save", Action.AS_DROP_DOWN_MENU);
  9.         setImageDescriptor (imgDescriptorSave);
  10.         setToolTipText ("Save the current configuration");
  11.         setMenuCreator (this);
  12.  
  13.         // create the manager for the drop down menu
  14.         m_menu = new MenuManager ();
  15.         m_menu.add (new Action ("Save", imgDescriptorSave)
  16.         {
  17.             @Override
  18.             public void run ()
  19.             {
  20.                 save ();
  21.             }
  22.         });
  23.  
  24.         m_menu.add (new Action ("Save as...", imgDescriptorSaveAs)
  25.         {
  26.             @Override
  27.             public void run ()
  28.             {
  29.                 saveAs ();
  30.             }
  31.         });
  32.     }
  33.  
  34.     @Override
  35.     public void run ()
  36.     {
  37.         save ();
  38.     }
  39.  
  40.     @Override
  41.     public void dispose ()
  42.     {
  43.         m_menu.dispose ();
  44.     }
  45.  
  46.     @Override
  47.     public Menu getMenu (Control parent)
  48.     {
  49.         return m_menu.createContextMenu (parent);
  50.     }
  51.  
  52.     @Override
  53.     public Menu getMenu (Menu parent)
  54.     {
  55.         return null;
  56.     }
  57. }