MATLAB: How to get a popupmenu with submenus which are related to various objects in the figure

associatedexampleMATLABmenuobjectpopupsubmenuuicontextmenu

I would like to get a popupmenu with submenus which are related to various objects in my figure. For example, I want to be able to right click on my surface object and pull up a menu that allows me to chose a colormap for that surface.

Best Answer

Since it is not possible to have a submenu to a popupmenu and it is sometimes not convinient to use a UIMenu for certain tasks, the option then is to use a UIContextMenu.
The usage of a UIContextMenu is much like that of a UIMenu. However, there are some additional steps that need to be performed. The following code illustrates the usage of this property.
% Create a Figure window
fighand=figure('color','black');
% Create a Surface Object and get its handle
p=surf(peaks);
axis off;
% Create a UIContextMenu object (with
% handle 'cm' and make it Visible
cm=uicontextmenu('visible','on');
% Set the context menu property of
% the surface object to this newly created
% context menu
set(p,'uicontextmenu',cm);
% Make a menu item 'h1' and label it 'Colormap'
h1=uimenu(cm,'label','Colormap');
% Make a menu item 'h1' and label it 'Shading'
h2=uimenu(cm,'label','Shading');
% Set the submenu labels and Callbacks of 'Colormap'
chsv=uimenu(h1,'label','HSV','callback','colormap(hsv)');
chot=uimenu(h1,'label','HOT','callback','colormap(hot)');
cbone=uimenu(h1,'label','BONE','callback','colormap(bone)');
ccopper=uimenu(h1,'label','COPPER','callback','colormap(copper)');
cflag=uimenu(h1,'label','FLAG','callback','colormap(flag)');
clines=uimenu(h1,'label','LINES','callback','colormap(lines)');
cccube=uimenu(h1,'label','COLORCUBE','callback','colormap(colorcube)');
cjet=uimenu(h1,'label','JET','callback','colormap(jet)');
cprism=uimenu(h1,'label','PRISM','callback','colormap(prism)');
cautumn=uimenu(h1,'label','AUTUMN','callback','colormap(autumn)');
cspring=uimenu(h1,'label','SPRING','callback','colormap(spring)');
cwinter=uimenu(h1,'label','WINTER','callback','colormap(winter)');
csummer=uimenu(h1,'label','SUMMER','callback','colormap(summer)');
% Set the submenu labels and Callbacks of 'Shading'
interpshading=uimenu(h2,'label','Interp','callback','shading interp');
flatshading=uimenu(h2,'label','Flat','callback','shading flat');
If you are using GUIDE and would like to define a UICONTEXTMENU for your objects, see the documentation obtained by typing the following command in the MATLAB Command Window::
web([docroot '/techdoc/creating_guis/ch_tools41.html#26257'])