Quantcast

Documentation Center

  • Trial Software
  • Product Updates

uicontextmenu

Create context menu

Syntax

handle = uicontextmenu('PropertyName',PropertyValue,...)

Description

handle = uicontextmenu('PropertyName',PropertyValue,...) creates a context menu, which is a menu that appears when the user right-clicks on a graphics object. See Uicontextmenu Properties for more information.

In its initial state, a context menu has no menu items. You create menu items within the context menu using the uimenu function. Menu items appear in the order in which the uimenu statements appear. You then associate a context menu with an object by specifying the handle of the context menu as the value for its UIContextMenu property.

Examples

The following statements define a context menu associated with a line on a graph. The menu items enable you to change the line style.

% Create axes and save handle
hax = axes;
% Plot three lines
plot(rand(20,3));
% Define a context menu; it is not attached to anything
hcmenu = uicontextmenu;
% Define callbacks for context menu 
% items that change linestyle
hcb1 = ['set(gco,''LineStyle'',''--'')'];
hcb2 = ['set(gco,''LineStyle'','':'')'];
hcb3 = ['set(gco,''LineStyle'',''-'')'];
% Define the context menu items and install their callbacks
item1 = uimenu(hcmenu,'Label','dashed','Callback',hcb1);
item2 = uimenu(hcmenu,'Label','dotted','Callback',hcb2);
item3 = uimenu(hcmenu,'Label','solid','Callback',hcb3);
% Locate line objects
hlines = findall(hax,'Type','line');
% Attach the context menu to each line
for line = 1:length(hlines)
    set(hlines(line),'uicontextmenu',hcmenu)
end

When you right-click on any line (or, on a Macintosh computer with a one-button mouse, press the Ctrl key and click), the context menu appears, as shown in the following figure.

To make context menus available immediately, attach them to lines at the time they are plotted. Therefore, when creating a GUI that uses such context menus, place code like the preceding in the callbacks that perform plotting for the GUI.

A best practice is to use function handles for callbacks. Only define callbacks as strings for simple actions. For example, you can add check marks to menu items (using the Checked uimenu property) to indicate the current style for each line. To manage the check marks, define the menu item callbacks as function handles. Place the code for the functions in the GUI code file rather than placing callback strings in the figure.

Generally, you need to attach context menus to lines at the time they are plotted in order to be sure that the menus are immediately available. Therefore, code such as the above could be placed in or called from the callbacks that perform plotting for the GUI.

Tutorials

See Context Menus in the MATLAB® Creating Graphical User Interfaces documentation.

See Also

| | |

Was this topic helpful?