| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB |
| Contents | Index |
| Learn more about MATLAB |
handle = uicontextmenu('PropertyName',PropertyValue,...)
handle = uicontextmenu('PropertyName',PropertyValue,...) creates a context menu, which is a menu that appears when the user right-clicks on a graphics object. See the Uicontextmenu Properties reference page for more information.
You create context menu items using the uimenu function. Menu items appear in the order the uimenu statements appear. You associate a context menu with an object using the UIContextMenu property for the object and specifying the context menu's handle as the property value.
These statements define a context menu associated with a line. When the user right clicks or presses Alt+click anywhere on the line, the menu appears. Menu items enable the user 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 the user right clicks or presses Alt+click on the line, the context menu appears, as shown in this 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 available to users at once. Therefore, code such as the above could be placed in or called from the callbacks that perform plotting for the GUI.
You should only define callbacks as strings if they need to perform simple actions. For example, if you wanted to add check marks to menu items (using the Checked uimenu property) to indicate the current style for a each line, you should define the menu item callbacks as function handles and place the code for them in the GUI's M-file rather than placing callback strings in the figure.
Context Menus in the MATLAB Creating Graphical User Interfaces documentation
uibuttongroup, uicontrol, uimenu, uipanel
![]() | Uibuttongroup Properties | Uicontextmenu Properties | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2009- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |