Define a Context Menu

This example shows how to define a context menu.

When to Use a Context Menu

Context menus are displayed when users right-click the graphics object for which you assign the context menu. Context menus enable you to provide choices to users for interaction with graphics objects.

Program a context menu when you want user to be able to:

  • Choose among specific options by right-clicking a graphics object.

  • Provide an indication of what each option is via the menu label.

  • Produce a specific result without knowing key combinations.

How to Define a Context Menu

  • Create a uicontextmenu object and save its handle.

  • Create each menu item using uimenu.

  • Define callbacks for each menu item in the context menu.

  • Parent the individual menu items to the context menu and assign the respective callback.

  • Assign the context menu handle to the UIContextMenu property of the object for which you are defining the context menu.

function cmHandle = defineCM
   cmHandle = uicontextmenu;
   uimenu(cmHandle,'Label','Wider','Callback',@increaseLW);
   uimenu(cmHandle,'Label','Inspect','Callback',@inspectLine);
end
function increaseLW(~,~)
% Increase line width
   h = gco;
   orgLW = h.LineWidth;
   h.LineWidth = orgLW+1;
end
function inspectLine(~,~)
% Open the property inspector
   h = gco;
   inspect(h)
end

The defineCM function returns the handle to the context menu that it creates. Assign this handle to the UIContextMenu property of the line objects as they are created by the plot function:

plot(rand(1,5),'UIContextMenu',defineCM)

Use a similar programming pattern for your specific requirements.