<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Menubar &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/menubar/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 09 Jan 2013 18:00:12 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
	<item>
		<title>Customizing the standard figure toolbar, menubar</title>
		<link>https://undocumentedmatlab.com/articles/customizing-standard-figure-toolbar-menubar?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-standard-figure-toolbar-menubar</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-standard-figure-toolbar-menubar#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 09 Jan 2013 18:00:12 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[Menubar]]></category>
		<category><![CDATA[Toolbar]]></category>
		<category><![CDATA[uitools]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3461</guid>

					<description><![CDATA[<p>The standard figure toolbar and menubar can easily be modified to include a list of recently-used files.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-standard-figure-toolbar-menubar">Customizing the standard figure toolbar, menubar</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/modifying-default-toolbar-menubar-actions" rel="bookmark" title="Modifying default toolbar/menubar actions">Modifying default toolbar/menubar actions </a> <small>The default Matlab figure toolbar and menu actions can easily be modified using simple pure-Matlab code. This article explains how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/figure-toolbar-components" rel="bookmark" title="Figure toolbar components">Figure toolbar components </a> <small>Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to access existing toolbar icons and how to add non-button toolbar components....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/figure-toolbar-customizations" rel="bookmark" title="Figure toolbar customizations">Figure toolbar customizations </a> <small>Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to customize the Matlab figure toolbar....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A few days ago, a client asked me to integrate an MRU (most-recently-used) file list in a Matlab GUI window. The naive approach was to add a new &#8220;Recent files&#8221; main menu, but this would look bad. Today I explain how to integrate the MRU list into the toolbar&#8217;s standard &#8220;Open File&#8221; button, as well as into the standard &#8220;File&#8221; main menu.</p>
<h3 id="Menubar">Customizing the standard &#8220;File&#8221; main menu</h3>
<p>Note: this relies on earlier articles about <a target="_blank" href="/articles/tag/menubar/">customizing the figure menubar</a>, so if you are not comfortable with this topic you might benefit from reading these earlier articles.<br />
Customizing the standard &#8220;File&#8221; main menu is easy. First, let&#8217;s find the &#8220;File&#8221; main menu&#8217;s handle, and add an MRU sub-menu directly to it:</p>
<pre lang='matlab'>
hFileMenu = findall(gcf, 'tag', 'figMenuFile');
hMruMenu = uimenu('Label','Recent files', 'Parent',hFileMenu);
</pre>
<p>Our new MRU menu item is created at the end (in this case, at the bottom of the &#8220;File&#8221; main menu list). Let&#8217;s move it upward, between &#8220;New&#8221; and &#8220;Open&#8230;&#8221;, by reordering <code>hFileMenu</code>&#8216;s <b>Children</b> menu items:</p>
<pre lang='matlab'>
hAllMenuItems = allchild(hFileMenu);
set(hFileMenu, 'Children',fliplr(hAllMenuItems([2:end-1,1,end])));  % place in 2nd position, just above the "Open" item
</pre>
<p>Now let&#8217;s fix the &#8220;Open&#8230;&#8221; menu item&#8217;s callback to point to our custom <i>openFile()</i> function (unfortunately, the &#8220;Open&#8230;&#8221; menu item has no tag, so we must rely on its label to get its handle):</p>
<pre lang='matlab'>
hOpenMenu = findall(hFileMenu, 'Label', '&Open...');
set(hOpenMenu, 'Callback',@openFile);
</pre>
<p>Finally, let&#8217;s add the MRU list as a sub-menu of the new <code>hMruMenu</code>. I assume that we have a <i>getMRU()</i> function in our code, which returns a cell-array of filenames:</p>
<pre lang='matlab'>
% Add the list of recent files, one item at a time
filenames = getMRU();
for fileIdx = 1 : length(filenames)
    uimenu(hMruMenu, 'Label',filenames{fileIdx}, 'Callback',{@openFile,filenames{fileIdx}});
end
</pre>
<p><center><figure style="width: 445px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" alt="Modified standard figure menu-bar" src="https://undocumentedmatlab.com/images/Menubar_File_Open.png" title="Modified standard figure menu-bar" width="445" height="182" /><figcaption class="wp-caption-text">Modified standard figure menu-bar</figcaption></figure></center><br />
<span id="more-3461"></span><br />
Clicking the main &#8220;Open&#8230;&#8221; menu item calls our <i>openFile()</i> function without the optional filename input argument, while selecting one of the MRU files will call the <i>openFile()</i> function with that specific filename as input. The <i>openFile()</i> function could be implemented something like this:</p>
<pre lang='matlab'>
% Callback for the open-file functionality (toolbar and menubar)
function openFile(hObject,eventData,filename)
    % If no filename specified, ask for it from the user
    if nargin < 3
        filename = uigetfile({'*.csv','Data files (*.csv)'}, 'Open data file');
        if isempty(filename) || isequal(filename,0)
            return;
        end
    end
    % Open the selected file and read the data
    data = readDataFile(filename);
    % Update the display
    updateGUI(data)
end
</pre>
<p>We can take this idea even further by employing <a target="_blank" href="/articles/html-support-in-matlab-uicomponents/">HTML formatting</a>, as I have shown in my <a target="_blank" href="/articles/customizing-menu-items-part-1/">first article of the menubar mini-series</a>:<br />
<center><figure style="width: 411px" class="wp-caption aligncenter"><img decoding="async" alt="HTML-rendered menu items" src="https://undocumentedmatlab.com/images/uimenu2b.png" title="HTML-rendered menu items" width="411" height="246"/><figcaption class="wp-caption-text">HTML-rendered menu items</figcaption></figure></center></p>
<h3 id="Toolbar">Customizing the standard toolbar's "Open File" button</h3>
<p>Note: this relies on earlier articles about <a target="_blank" href="/articles/tag/toolbar/">customizing the figure toolbar</a>, so if you are not comfortable with this topic you might benefit from reading these earlier articles.<br />
The basic idea here is to replace the standard toolbar's "Open File" pushbutton with a new <a target="_blank" href="/articles/uisplittool-uitogglesplittool/">uisplittool</a> button that will contain the MRU list in its picker-menu.<br />
The first step is to get the handle of the toolbar's "Open File" button:</p>
<pre lang='matlab'>
hOpen = findall(gcf, 'tooltipstring', 'Open File');
hOpen = findall(gcf, 'tag', 'Standard.FileOpen');  % Alternative
</pre>
<p>The second alternative is better for non-English Matlab installations where the tooltip text may be different, or in cases where we might have another GUI control with this specific tooltip. On the other hand, the <code>'Standard.FileOpen'</code> tag may be different in different Matlab releases. So choose whichever option is best for your specific needs.<br />
Assuming we have a valid (non-empty) <code>hOpen</code> handle, we get its properties data for later use:</p>
<pre lang='matlab'>
open_data = get(hOpen);
hToolbar = open_data.Parent;
</pre>
<p>We have all the information we need, so we can now simply delete the existing toolbar open button, and create a new split-button with the properties data that we just got:</p>
<pre lang='matlab'>
delete(hOpen);
hNewOpen = uisplittool('Parent',hToolbar, ...
                       'CData',open_data.CData, ...
                       'Tooltip',open_data.TooltipString, ...
                       'ClickedCallback',@openFile);
</pre>
<p>As with the menubar, the button is now created, but it appears on the toolbar&#8217;s right edge. Let&#8217;s move it to the far left. We could theoretically reorder <code>hToolbar</code>&#8216;s <b>Children</b> as for the menubar above, but Matlab has an internal bug that causes some toolbar buttons to misbehave upon rearranging. Using Java solves this:</p>
<pre lang='matlab'>
drawnow;  % this innocent drawnow is *very* important, otherwise Matlab might crash!
jToolbar = get(get(hToolbar,'JavaContainer'),'ComponentPeer');
jButtons = jToolbar.getComponents;
jToolbar.setComponentZOrder(jButtons(end),2);  % Move to the position between "New" and "Save"
jToolbar.revalidate;  % update the toolbar's appearance (drawnow will not do this)
</pre>
<p>Finally, let&#8217;s add the list of recent files to the new split-button&#8217;s picker menu:</p>
<pre lang='matlab'>
% (Use the same list of filenames as for the menubar's MRU list)
jNewOpen = get(hNewOpen,'JavaContainer');
jNewOpenMenu = jNewOpen.getMenuComponent;
for fileIdx = 1 : length(filenames)
    jMenuItem = handle(jNewOpenMenu.add(filenames{fileIdx}),'CallbackProperties');
    set(jMenuItem,'ActionPerformedCallback',{@openFile,filenames{fileIdx}});
end
</pre>
<p><center><figure style="width: 445px" class="wp-caption aligncenter"><img decoding="async" alt="Modified standard figure toolbar" src="https://undocumentedmatlab.com/images/Toolbar_Open_File.png" title="Modified standard figure toolbar" width="447" height="143" /><figcaption class="wp-caption-text">Modified standard figure toolbar</figcaption></figure></center><br />
Clicking the main Open button calls our <i>openFile()</i> function without the optional filename input argument, while clicking the picker button (to the right of the main Open button) and selecting one of the files will call the <i>openFile()</i> function with that specific filename as input.<br />
That&#8217;s it. Quite painless in fact. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-standard-figure-toolbar-menubar">Customizing the standard figure toolbar, menubar</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/modifying-default-toolbar-menubar-actions" rel="bookmark" title="Modifying default toolbar/menubar actions">Modifying default toolbar/menubar actions </a> <small>The default Matlab figure toolbar and menu actions can easily be modified using simple pure-Matlab code. This article explains how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/figure-toolbar-components" rel="bookmark" title="Figure toolbar components">Figure toolbar components </a> <small>Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to access existing toolbar icons and how to add non-button toolbar components....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/figure-toolbar-customizations" rel="bookmark" title="Figure toolbar customizations">Figure toolbar customizations </a> <small>Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to customize the Matlab figure toolbar....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-standard-figure-toolbar-menubar/feed</wfw:commentRss>
			<slash:comments>12</slash:comments>
		
		
			</item>
		<item>
		<title>Disabling menu entries in deployed docked figures</title>
		<link>https://undocumentedmatlab.com/articles/disabling-menu-entries-in-deployed-docked-figures?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=disabling-menu-entries-in-deployed-docked-figures</link>
					<comments>https://undocumentedmatlab.com/articles/disabling-menu-entries-in-deployed-docked-figures#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 14 Nov 2012 18:00:46 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Listeners]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Alexander Mering]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[Compiler]]></category>
		<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Docking]]></category>
		<category><![CDATA[FindJObj]]></category>
		<category><![CDATA[JavaFrame]]></category>
		<category><![CDATA[Listener]]></category>
		<category><![CDATA[Menubar]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3344</guid>

					<description><![CDATA[<p>Matlab's standard menu items can and should be removed from deployed  docked figures. This article explains how. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/disabling-menu-entries-in-deployed-docked-figures">Disabling menu entries in deployed docked figures</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/docking-figures-in-compiled-applications" rel="bookmark" title="Docking figures in compiled applications">Docking figures in compiled applications </a> <small>Figures in compiled applications cannot officially be docked since R2008a, but this can be done using a simple undocumented trick....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-pure-java-gui-in-deployed-matlab-apps" rel="bookmark" title="Using pure Java GUI in deployed Matlab apps">Using pure Java GUI in deployed Matlab apps </a> <small>Using pure-Java GUI in deployed Matlab apps requires a special yet simple adaptation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jgraph-in-matlab-figures" rel="bookmark" title="JGraph in Matlab figures">JGraph in Matlab figures </a> <small>JGraph is a powerful open-source Java library that can easily be integrated in Matlab figures. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Last week I presented an <a target="_blank" href="/articles/removing-user-preferences-from-deployed-apps/">article</a> explaining how to solve an issue with deployed (compiled) Matlab applications. Today I&#8217;d like to welcome guest blogger <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/208302">Alexander Mering</a>, who will explain how to disable standard Matlab menu items in deployed docked Matlab figures. Alexander has been an avid follower of this blog, and from his <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/search_results?dur=all&#038;search_string=authorid%3A146471">CSSM posts</a> we can tell that he&#8217;s been heavily using advanced GUI features presented in this blog. His article today nicely shows how we can use different building-blocks presented in different articles in this blog, to achieve something new and useful.</i><br />
As Yair pointed out in many occasions, the power of Matlab could be greatly enhanced using the underlying Java mechanism. To me, while developing a larger standalone tool for technical calculations, these hints are worth a mint (as I guess for many of you).<br />
One of these very useful hints is the ability to <a target="_blank" href="/articles/docking-figures-in-compiled-applications/">dock figure windows in standalone applications</a>. This perfectly fits to my understanding of a &#8220;clean desktop&#8221;, i.e., having as less as possible separate windows. Since in many calculations dozens of figures are generated, the desktop gets up crowded very fast &#8211; if these are not grouped. So docking is essential (at least for me). Unfortunately there seems to be a serious problem with the resulting menu entries (at least in R2011b on Win XP), leading to a crash of the standalone application. Based on the posts by Yair, I will sketch a possible route to avoid this issue.</p>
<h3 id="symptom">The symptom</h3>
<p>In the compiled application, docking could be accomplished by accessing the figure frame&#8217;s underlying Java level:</p>
<pre lang='matlab'>
% get java frame for sophisticated modifications
jframe = get(handle(figure_handle), 'JavaFrame');
% allow docking
jframe.fHG1Client.setClientDockable(true)
</pre>
<p>Using this modification, the user is now allowed to dock and undock the figures manually. For initial docking of the figure,</p>
<pre lang='matlab'>javaFrame.fHG1Client.setClientWindowStyle(true,false)</pre>
<p>could be used during figure creation. Unfortunately, there are menu entries in the Figures container which are either unwanted (since not usable) or even directly crash the standalone applications:<br />
<span id="more-3344"></span><br />
<center><figure style="width: 320px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Useless Debug menu items in deployed applications" src="https://undocumentedmatlab.com/images/Useless_debug_menu.png" title="Useless Debug menu items in deployed applications" width="320" height="267" /><figcaption class="wp-caption-text">Useless Debug menu items in deployed applications</figcaption></figure></center><br />
<center><figure style="width: 504px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Menu items crashing deployed applications" src="https://undocumentedmatlab.com/images/Buggy_desktop_menu.png" title="Menu items crashing deployed applications" width="504" height="241" /><figcaption class="wp-caption-text">Menu items crashing deployed applications</figcaption></figure></center><br />
Since crashing menu entries will be found and used by end-users (though these are somehow hidden), these prohibit the usage of the docking feature as long as these could be invoked. So how can we disable / remove these menu items?</p>
<h3 id="unsuccessful">The unsuccessful solution</h3>
<p>Unfortunately, the straight forward solution of getting the handle to the Figures containers&#8217; menu bar and remove the unwanted items does not work. The reason for this is the (to me unexpected behavior) that the menu bar seems to be rebuilt whenever a figure is docked/undocked.<br />
This is actually the same behavior that automatically rebuilds the Editor&#8217;s menu bar whenever an editor file is added/removed. The Editor container is basically the same docking container as the Figures container, as shown by Yair&#8217;s <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/16650-setfigdockgroup"><i><b>setFigDockGroup</b></i> utility</a>:<br />
<center><figure style="width: 504px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Docking a figure in the Editor container (group)" src="https://undocumentedmatlab.com/images/setFigDockGroup.png" title="Docking a figure in the Editor container (group)" width="504" height="551" /><figcaption class="wp-caption-text">Docking a figure in the Editor container (group)</figcaption></figure></center><br />
Therefore, removing unwanted menu items only helps until the next figure docking/undocking. To make it even worse: also pressing any of the buttons within the document bar (if having more than one figure) somehow rebuilds the entire menu structure, reverting our changes. So the solution becomes a bit more complex.</p>
<h3 id="solution">The working solution</h3>
<p>For the working solution, many pieces presented by Yair should be put together. The first piece results from the question how to detect a dock/undock event. Since no such callback is defined, we need to use a property listener as Yair showed in his post about the <a target="_blank" href="/articles/continuous-slider-callback/">continuous slider callback</a>:</p>
<pre lang='matlab'>
% listen to the WindowStyle property to detect docking / undocking events
hProp = findprop(handle(figure_handle),'WindowStyle');  % a schema.prop object
% if the event occurs, invoke the callback
hlistener = handle.listener(handle(figure_handle), hProp, 'PropertyPostSet',{@(source, event) Callback_DockingFcn});
% attach listener to the GUI since it needs to be known (as long as the figure exists)
setappdata(figure_handle, 'Handle_Listener', hlistener);
</pre>
<p>Now, whenever the figure&#8217;s <b>WindowStyle</b> property (which controls the docking state) is changed, our docking callback is invoked.<br />
The next piece of the puzzle takes care of the menu rebuild whenever any document bar button is pressed. To overcome this behavior, the idea is to define the <b>MousePressed</b> callback of theses buttons to (again) invoke the docking callback. This is necessary for two reasons: First, pressing the button (i.e., changing the current figure) rebuilds the menu, overwriting our changed menu entries. Secondly, all other buttons are also somehow rebuilt and the callbacks are removed if a new figure is docked.<br />
The handles to the document bar buttons could be found using Yair&#8217;s <a target="_blank" href="/articles/findjobj-find-underlying-java-object/"><i><b>findjobj</b></i> utility</a>. We have already seen that the Editor container is analogous to the Figures docking container. So let&#8217;s use the method described by Yair for <a target="_blank" href="/articles/accessing-the-matlab-editor/">accessing the Editor container</a>, to access the Figures container:</p>
<pre lang='matlab'>
figures_container = javaObjectEDT(matlab_instance.getGroupContainer('Figures'));
figures_frame = javaObjectEDT(figures_container.getTopLevelAncestor);
</pre>
<p>Once we get the Java Frame for the Figures container, the buttons could be found by digging through its children. This finally allows to set the callback using</p>
<pre lang='matlab'>
DTDocumentBar = javaObjectEDT(figures_frame.getRootPane.getLayeredPane.getComponent(1).getComponent(1).getComponent(0).getComponent(0).getComponent(1).getComponent(0));
ContentPanel = javaObjectEDT(DTDocumentBar.getComponent(0).getComponent(0).getViewport.getView);
if ~isempty(ContentPanel.getComponents) % less than two documents are open and no DTDocumentbar exists
    drawnow; pause(0.05)
    GroupPanel = javaObjectEDT(ContentPanel.getComponent(0));
    GroupPanel_Elements = javaObjectEDT(GroupPanel.getComponents);
    % change the MousePressed Callback for each of the buttons to invoke the function which disables the menu
    for n = 1 : GroupPanel.getComponentCount
        thisElement = GroupPanel_Elements(n);
        if isequal(char(thisElement.getClass.toString), 'class com.mathworks.widgets.desk.DTDocumentBar$DocumentButton')
            set(handle(thisElement, 'CallbackProperties'), 'MousePressedCallback', {@(source, event) Cbrake_Callback_Diagrams_DockingFcn})
        end
    end
    drawnow; pause(0.05)
end
</pre>
<p>where the loop runs through the current buttons in the document bar.<br />
As the last step of our procedure, we finally remove (or disable) the menu entries which are unwanted. This is achieved by extracting the handle to the Figures menu by:</p>
<pre lang='matlab'>figures_menu = javaObjectEDT(figures_frame.getJMenuBar);</pre>
<p>Running through the menu items, searching for the unwanted entries (as long as they have pre-defined <a target="_blank" href="/articles/modifying-default-toolbar-menubar-actions/">menu-item names</a>) at the end sets us into the position to take care of the menu items:</p>
<pre lang='matlab'>
% run through top-level menu items
for n = 1 : figures_menu.getMenuCount
    % completely deactivate Debugging options
    if isequal(char(figures_menu.getMenu(n-1).getName), 'DesktopDebugMenu')
        DesktopDebugMenuPos = n - 1;
    end
    % Remove some items from the Desktop menu
    if isequal(char(figures_menu.getMenu(n-1).getName), 'DesktopMenu')
        desktop_menu = javaObjectEDT(figures_menu.getMenu(n-1));
        DeletePos = [];
        for m = 1: desktop_menu.getMenuComponentCount
            if ismember({char(desktop_menu.getMenuComponent(m-1).getName)}, ...
                        {'ToggleFigure PaletteCheckBoxMenuItem', 'TogglePlot BrowserCheckBoxMenuItem', 'ToggleProperty EditorCheckBoxMenuItem'})
                DeletePos(end+1) = m - 1;
            end
        end
        for m = length(DeletePos) : -1 : 1
            desktop_menu.remove(DeletePos(m))
        end
    end
end
% finally remove the "Debug" menu
if ~isempty(DesktopDebugMenuPos)
    figures_menu.remove(DesktopDebugMenuPos)
end
</pre>
<p>Since this callback is invoked whenever a figure is docked/undocked, or the currently shown figure is changed (by pressing the document bar button), all unwanted menu items within the Figures menu could be removed.<br />
As a result, the new Figures container menu looks like:<br />
<center><figure style="width: 319px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Deployed menu without unwanted items" src="https://undocumentedmatlab.com/images/Reduced_figures_menu.png" title="Deployed menu without unwanted items" width="319" height="205" /><figcaption class="wp-caption-text">Deployed menu without unwanted items</figcaption></figure></center></p>
<h3 id="remarks">Remarks</h3>
<p>I must admit that above solution is still imperfect. For instance, sometimes there is a larger delay between the docking (or button press event) and the removing of the menu item. Nevertheless, this solution allows me to distribute my standalone with docked figures without having menu items directly leading to a fatal error.<br />
Obviously, the solution has some positive side effects:</p>
<ul>
<li>As could be seen from the screen shot, the Matlab desktop becomes available also within your compiled applications. This might be wanted. If not, it could be removed the same way as the other menu items. One drawback of making the desktop available should be mentioned: In my tests, the standalone Matlab desktop shows the whole list of recent files I have in the Matlab editor at compile time. This is somehow ugly but not that problematic.</li>
<li>Additional menu items could be added, giving more possibilities for modifications.</li>
</ul>
<p>I have uploaded a first version of the docking and creation functions, together with a small test project, to the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/39026-figures-menu-adaption-for-standalone-applications">Matlab file Exchange</a>. Readers are welcome to download the code and send me improvement suggestions. Or you could simply <a href="/articles/disabling-menu-entries-in-deployed-docked-figures#respond">leave a comment</a> below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/disabling-menu-entries-in-deployed-docked-figures">Disabling menu entries in deployed docked figures</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/docking-figures-in-compiled-applications" rel="bookmark" title="Docking figures in compiled applications">Docking figures in compiled applications </a> <small>Figures in compiled applications cannot officially be docked since R2008a, but this can be done using a simple undocumented trick....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-pure-java-gui-in-deployed-matlab-apps" rel="bookmark" title="Using pure Java GUI in deployed Matlab apps">Using pure Java GUI in deployed Matlab apps </a> <small>Using pure-Java GUI in deployed Matlab apps requires a special yet simple adaptation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jgraph-in-matlab-figures" rel="bookmark" title="JGraph in Matlab figures">JGraph in Matlab figures </a> <small>JGraph is a powerful open-source Java library that can easily be integrated in Matlab figures. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/disabling-menu-entries-in-deployed-docked-figures/feed</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing menu items part 3</title>
		<link>https://undocumentedmatlab.com/articles/customizing-menu-items-part-3?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-menu-items-part-3</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-menu-items-part-3#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 09 May 2012 18:00:05 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Icons]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[JavaFrame]]></category>
		<category><![CDATA[Menubar]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2909</guid>

					<description><![CDATA[<p>Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-3">Customizing menu items part 3</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-2" rel="bookmark" title="Customizing menu items part 2">Customizing menu items part 2 </a> <small>Matlab menu items can be customized in a variety of useful ways using their underlying Java object. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items" rel="bookmark" title="Customizing listbox/combobox items">Customizing listbox/combobox items </a> <small>Matlab listboxes can be customized using custom Java cell-renderers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-1" rel="bookmark" title="Customizing menu items part 1">Customizing menu items part 1 </a> <small>Matlab menus can be customized in a variety of undocumented manners - first article of a series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-uitree-nodes" rel="bookmark" title="Customizing uitree nodes &#8211; part 1">Customizing uitree nodes &#8211; part 1 </a> <small>This article describes how to customize specific nodes of Matlab GUI tree controls created using the undocumented uitree function...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In the past weeks I&#8217;ve shown how Matlab menus can be customized in a variety of undocumented manners, using HTML, <a target="_blank" href="/articles/customizing-menu-items-part-1/">pure Matlab</a>, and <a target="_blank" href="/articles/customizing-menu-items-part-2/">Java</a>. Today I conclude this mini-series with an article that explains how to use the underlying Java object to customize menu item icons. Menu customizations are explored in depth in section 4.6 of my <a target="_blank" href="/matlab-java-book/">book</a>.</p>
<h3 id="underlying">A reminder: accessing the underlying Java object</h3>
<p>Matlab menus (<i><b>uimenu</b></i>) are basically simple wrappers for the much more powerful and flexible Java Swing <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/menu.html"><code>JMenu</code> and <code>JMenuItem</code></a> on which they are based.  Many important functionalities that are available in Java menus are missing from the Matlab <i><b>uimenu</b></i>s.<br />
Getting the Java reference for the figure window&#8217;s main menu is very easy:</p>
<pre lang='matlab'>
jFrame = get(handle(hFig),'JavaFrame');
try
    % R2008a and later
    jMenuBar = jFrame.fHG1Client.getMenuBar;
catch
    % R2007b and earlier
    jMenuBar = jFrame.fFigureClient.getMenuBar;
end
</pre>
<p>There are many customizations that can only be done using the Java handle: setting icons, several dozen callback types, tooltips, background color, font, text alignment, and so on. etc. Interested readers may wish to <i><b>get</b></i>/<i><b>set</b></i>/<i><b>inspect</b></i>/<i><b>methodsview</b></i>/<i><b><a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect-display-methods-properties-callbacks-of-an-object">uiinspect</a></b></i> the <code>jSave</code> reference handle and/or to read the documentation for <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/javax/swing/JMenuItem.html"><code>JMenuItem</code></a>. Today&#8217;s article will focus on icon customizations.</p>
<h3 id="simple">Setting simple menu item icons</h3>
<p>Many of Matlab&#8217;s icons reside in either the <i>[matlabroot &#8216;/toolbox/matlab/icons/&#8217;]</i> folder or the <i>[matlabroot &#8216;/java/jar/mwt.jar&#8217;]</i> file (a JAR file is simply a zip file that includes Java classes and resources such as icon images). Let us create icons from the latter, to keep a consistent look-and-feel with the rest of Matlab (we could just as easily use our own external icon files):</p>
<pre lang='matlab'>
% External icon file example
jSave.setIcon(javax.swing.ImageIcon('C:\Yair\save.gif'));
% JAR resource example
jarFile = fullfile(matlabroot,'/java/jar/mwt.jar');
iconsFolder = '/com/mathworks/mwt/resources/';
iconURI = ['jar:file:/' jarFile '!' iconsFolder 'save.gif'];
iconURI = java.net.URL(iconURI);  % not necessary for external files
jSave.setIcon(javax.swing.ImageIcon(iconURI));
</pre>
<p>Note that setting a menu item&#8217;s icon automatically re-aligns all other items in the menu, including those that do not have an icon (an internal bug that was introduced in R2010a causes a misalignment, as shown below):<br />
<center><figure style="width: 230px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Menu item with a custom Icon (R2009b)" src="https://undocumentedmatlab.com/images/uimenu3.png" title="Menu item with a custom Icon (R2009b)" width="230" height="120"/><figcaption class="wp-caption-text">Menu item with a custom <b>Icon</b> (R2009b)</figcaption></figure> &nbsp;&nbsp;&nbsp; <figure style="width: 227px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="...and the same in R2010a onward" src="https://undocumentedmatlab.com/images/uimenu3b.png" title="...and the same in R2010a onward" width="227" height="120"/><figcaption class="wp-caption-text">...and the same in R2010a onward</figcaption></figure></center></p>
<h3 id="checkmark">Checkmark icon</h3>
<p>The empty space on the left of the menu is reserved for the check mark. Each Matlab menu item is check-able, since it is an object that extends the <code>com.mathworks.mwswing.MJCheckBoxMenuItem</code> class. I have not found a way to eliminate this empty space, which is really unnecessary in the File-menu case (it is only actually necessary in the View and Tools menus). Note that if an icon is set for the item, both the icon and the checkmark will be displayed, side by side.<br />
The check mark is controlled by the <b>State</b> property of the Java object (which accepts logical true/false values), or the <b>Checked</b> property of the Matlab handle (which accepts the regular &#8216;on&#8217;/&#8217;off&#8217; string values):</p>
<pre lang='matlab'>
% Set the check mark at the Matlab level
set(findall(hFig,'tag','figMenuFileSave'), 'Checked','on');
% Equivalent - set the checkmark at the Java level
jSave.setState(true);
</pre>
<p><center><figure style="width: 185px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="State = true, Icon = [ ]" src="https://undocumentedmatlab.com/images/uimenu_save_checked1.png" title="State = true, Icon = [ ]" width="185" height="138"/><figcaption class="wp-caption-text"><b>State</b> = true, <b>Icon</b> = &#091; &#093;</figcaption></figure> &nbsp;&nbsp;&nbsp; <figure style="width: 205px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="State = true, Icon = custom" src="https://undocumentedmatlab.com/images/uimenu_save_checked2.png" title="State = true, Icon = custom" width="205" height="137"/><figcaption class="wp-caption-text"><b>State</b> = true, <b>Icon</b> = custom</figcaption></figure></center></p>
<h3 id="custom">Customizing menu icons</h3>
<p>Icons can be customized: modify the gap between the icon and the label with the <b>IconTextGap</b> property (default = 4 [pixels]); place icons to the right of the label by setting <b>HorizontalTextPosition</b> to <code>jSave.LEFT</code> (=2), or centered using <code>jSave.CENTER</code> (=0). Note that the above-mentioned misalignment bug does not appear in these cases:<br />
<center><figure style="width: 222px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="jSave.setHorizontalTextPosition(jSave.LEFT)" src="https://undocumentedmatlab.com/images/uimenu4.png" title="jSave.setHorizontalTextPosition(jSave.LEFT)" width="222" height="121"/><figcaption class="wp-caption-text"><code>jSave.setHorizontalTextPosition<br />(jSave.LEFT)</code></figcaption></figure> &nbsp;&nbsp;&nbsp; <figure style="width: 223px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="jSave.setHorizontalTextPosition(jSave.CENTER)" src="https://undocumentedmatlab.com/images/uimenu5.png" title="jSave.setHorizontalTextPosition(jSave.CENTER)" width="223" height="120"/><figcaption class="wp-caption-text"><code>jSave.setHorizontalTextPosition<br />(jSave.CENTER)</code></figcaption></figure></center><br />
Note how the label text can be seen through (or on top of) the icon when it is centered. This feature can be used to create stunning menu effects as shown below. Note how the width and height of the menu item automatically increased to accommodate my new 77&#215;31 icon size (icons are normally sized 16&#215;16 pixels):<br />
<center><figure style="width: 285px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Overlaid icon (HorizontalTextPosition = CENTER)" src="https://undocumentedmatlab.com/images/uimenu6.png" title="Overlaid icon (HorizontalTextPosition = CENTER)" width="285" height="136"/><figcaption class="wp-caption-text">Overlaid icon (<b>HorizontalTextPosition</b> = CENTER)</figcaption></figure></center><br />
To resize an icon programmatically before setting it in a Java component, we can use the following example:</p>
<pre lang='matlab'>
myIcon = fullfile(matlabroot,'/toolbox/matlab/icons/matlabicon.gif');
imageToolkit = java.awt.Toolkit.getDefaultToolkit;
iconImage = imageToolkit.createImage(myIcon);
iconImage = iconImage.getScaledInstance(32,32,iconImage.SCALE_SMOOTH);
jSave.setIcon(javax.swing.ImageIcon(iconImage));
</pre>
<p>Remember when rescaling images, particularly small ones with few pixels, that it is always better to shrink than to enlarge images: enlarging a small icon image might introduce a significant pixelization effect:<br />
<center><figure style="width: 90px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="16x16 icon image resized to 32x32" src="https://undocumentedmatlab.com/images/button_icon2.png" title="16x16 icon image resized to 32x32" width="90" height="90"/><figcaption class="wp-caption-text">16x16 icon image resized to 32x32</figcaption></figure></center><br />
Separate icons can be specified for a different appearance during mouse hover (<b>RolloverIcon</b>; requires <b>RolloverEnabled</b>=1), item click/press (<b>PressedIcon</b>), item selection (<b>SelectedIcon</b>, <b>RolloverSelectedIcon</b>, <b>DisabledSelectedIcon</b>), and disabled menu item (<b>DisabledIcon</b>). All these properties are empty ([]) by default, which applies a predefined default variation (image color filter) to the main item&#8217;s Icon. For example, let us modify <b>DisabledIcon</b>:</p>
<pre lang='matlab'>
myIcon = 'C:\Yair\Undocumented Matlab\Images\save_disabled.gif';
jSaveAs.setDisabledIcon(javax.swing.ImageIcon(myIcon));
jSaveAs.setEnabled(false);
</pre>
<p><center><figure style="width: 120px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Enabled, main Icon" src="https://undocumentedmatlab.com/images/uimenu7a.png" title="Enabled, main Icon" width="120" height="135"/><figcaption class="wp-caption-text">Enabled, main <b>Icon</b></figcaption></figure> &nbsp;&nbsp;&nbsp; <figure style="width: 160px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Disabled, default Icon variation" src="https://undocumentedmatlab.com/images/uimenu7b.png" title="Disabled, default Icon variation" width="120" height="135"/><figcaption class="wp-caption-text">Disabled, default <b>Icon</b> variation</figcaption></figure> &nbsp;&nbsp;&nbsp; <figure style="width: 170px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Disabled, custom DisabledIcon" src="https://undocumentedmatlab.com/images/uimenu7c.png" title="Disabled, custom DisabledIcon" width="120" height="135"/><figcaption class="wp-caption-text">Disabled, custom <b>DisabledIcon</b></figcaption></figure></center><br />
Note the automatic graying of disabled menu items, including their icon. This effect can also be achieved programmatically using the static methods in <code>com.mathworks.mwswing.IconUtils</code>: <i>changeIconColor(), createBadgedIcon(), createGhostedIcon()</i>, and <i>createSelectedIcon()</i>. When we use a non-default custom <b>DisabledIcon</b>, it is used instead of the gray icon variant.<br />
This concludes my mini-series of customizing menus in Matlab. If you have used any nifty customization that I have not mentioned, please post a comment about it <a href="/articles/customizing-menu-items-part-3/#respond">below</a>.<br />
<span class="alignleft" id="ken_mike"><img loading="lazy" decoding="async" alt="Ken &#038; Mike" src="https://undocumentedmatlab.com/images/ken_and_mike.png" title="Ken &#038; Mike" width="98" height="83"/></span>In an unrelated note, I would like to extend good wishes to Mike Katz, who has left the MathWorks mobile development team to join Kinvey a few days ago. Mike has been with MathWorks since 2005 and has been responsible for maintaining the official <a target="_blank" rel="nofollow" href="http://blogs.mathworks.com/desktop/">MATLAB Desktop blog</a>, together with <a target="_blank" href="/articles/gui-integrated-browser-control/">Ken Orr</a>. I&#8217;m not sure yet which direction the Desktop blog will take, and by whom, but in any case it won&#8217;t be the same. You&#8217;re both missed, Mike &#038; Ken!</p>
<p />&nbsp;</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-3">Customizing menu items part 3</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-2" rel="bookmark" title="Customizing menu items part 2">Customizing menu items part 2 </a> <small>Matlab menu items can be customized in a variety of useful ways using their underlying Java object. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items" rel="bookmark" title="Customizing listbox/combobox items">Customizing listbox/combobox items </a> <small>Matlab listboxes can be customized using custom Java cell-renderers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-1" rel="bookmark" title="Customizing menu items part 1">Customizing menu items part 1 </a> <small>Matlab menus can be customized in a variety of undocumented manners - first article of a series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-uitree-nodes" rel="bookmark" title="Customizing uitree nodes &#8211; part 1">Customizing uitree nodes &#8211; part 1 </a> <small>This article describes how to customize specific nodes of Matlab GUI tree controls created using the undocumented uitree function...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-menu-items-part-3/feed</wfw:commentRss>
			<slash:comments>39</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing menu items part 2</title>
		<link>https://undocumentedmatlab.com/articles/customizing-menu-items-part-2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-menu-items-part-2</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-menu-items-part-2#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 02 May 2012 11:57:38 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[JavaFrame]]></category>
		<category><![CDATA[Menubar]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2902</guid>

					<description><![CDATA[<p>Matlab menu items can be customized in a variety of useful ways using their underlying Java object. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-2">Customizing menu items part 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-3" rel="bookmark" title="Customizing menu items part 3">Customizing menu items part 3 </a> <small>Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items" rel="bookmark" title="Customizing listbox/combobox items">Customizing listbox/combobox items </a> <small>Matlab listboxes can be customized using custom Java cell-renderers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-1" rel="bookmark" title="Customizing menu items part 1">Customizing menu items part 1 </a> <small>Matlab menus can be customized in a variety of undocumented manners - first article of a series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-editboxes" rel="bookmark" title="Customizing editboxes">Customizing editboxes </a> <small>Matlab's editbox can be customized in many useful manners...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Last week I <a target="_blank" href="/articles/customizing-menu-items-part-1/">explained</a> how to customize Matlab&#8217;s menu items using some undocumented tricks that do not need Java. Today I will show how using just a tiny bit of Java magic powder we can add much more complex customizations to menu items. Menu customizations are explored in depth in section 4.6 of my <a target="_blank" href="/matlab-java-book/">book</a>.</p>
<h3 id="underlying">Accessing the underlying Java object</h3>
<p>Matlab menus (<i><b>uimenu</b></i>) are basically simple wrappers for the much more powerful and flexible Java Swing <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/menu.html"><code>JMenu</code> and <code>JMenuItem</code></a> on which they are based.  Many important functionalities that are available in Java menus are missing from the Matlab <i><b>uimenu</b></i>s.<br />
Getting the Java reference for the figure window&#8217;s main menu is very easy:</p>
<pre lang='matlab'>
jFrame = get(handle(hFig),'JavaFrame');
try
    % R2008a and later
    jMenuBar = jFrame.fHG1Client.getMenuBar;
catch
    % R2007b and earlier
    jMenuBar = jFrame.fFigureClient.getMenuBar;
end
</pre>
<p>Note that we have used the figure handle&#8217;s hidden <a target="_blank" href="/articles/minimize-maximize-figure-window/#JavaFrame"><b>JavaFrame</b> property</a>, accessed through the reference&#8217;s <i><b>handle</b></i>() wrapper, to prevent an annoying warning message.<br />
There are many customizations that can only be done using the Java handle: setting icons, several dozen callback types, tooltips, background color, font, text alignment, and so on. etc. Interested readers may wish to <i><b>get</b></i>/<i><b>set</b></i>/<i><b>inspect</b></i>/<i><b>methodsview</b></i>/<i><b><a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect-display-methods-properties-callbacks-of-an-object">uiinspect</a></b></i> the <code>jSave</code> reference handle and/or to read the documentation for <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/javax/swing/JMenuItem.html"><code>JMenuItem</code></a>. Some useful examples are provided below.</p>
<h3 id="dynamic">Dynamic menu behavior</h3>
<p>As a first example of Java-based customization, let us add DHTML-like behavior to the menu, such that the menu items will automatically be displayed when the mouse hovers over the item, without waiting for a user mouse click. First, get the <code>jMenuBar</code> reference as described above. Now, set the <b>MouseEnteredCallback</b> to automatically simulate a user mouse click on each menu item using its <i>doClick()</i> method. Setting the callback should be done separately to each of the top-level menu components:</p>
<pre lang='matlab'>
for menuIdx = 1 : jMenuBar.getComponentCount
    jMenu = jMenuBar.getComponent(menuIdx-1);
    hjMenu = handle(jMenu,'CallbackProperties');
    set(hjMenu,'MouseEnteredCallback','doClick(gcbo)');
end
</pre>
<p>Note that using this mechanism may be awkward if the top-level menu does not have a sub-menu but is rather a stand-alone menu item. For example, if the top-level menu-item &#8220;Help&#8221; is a stand-alone menu button (i.e., there are no help menu-items, just the single Help item), then moving the mouse over this item will trigger the help event, although the user did not actually click on the item. To prevent this behavior, we should modify the code snippet above to only work on those menu items that have sub-items.</p>
<h3 id="accelerator">Custom accelerator shortcut keys</h3>
<p>As another example, Matlab automatically assigns a non-modifiable keyboard accelerator key modifier of <ctrl>, while JMenus allow any combination of Alt/Ctrl/Shift/Meta (depending on the platform). Let us modify the default File/Save accelerator key from &#8216;Ctrl-S&#8217; to &#8216;Alt-Shift-S&#8217; as an example. We need a reference for the &#8220;Save&#8221; menu item. Note that unlike regular Java components, menu items are retrieved using the <i>getMenuComponent()</i> method and not <i>getComponent()</i>:</p>
<pre lang='matlab'>
% File main menu is the first main menu item => index=0
jFileMenu = jMenuBar.getComponent(0);
% Save menu item is the 5th menu item (separators included)
jSave = jFileMenu.getMenuComponent(4); %Java indexes start with 0!
inspect(jSave) 	% just to be sure: label='Save' => good!
% Finally, set a new accelerator key for this menu item:
jAccelerator = javax.swing.KeyStroke.getKeyStroke('alt shift S');
jSave.setAccelerator(jAccelerator);
</pre>
<p>That is all there is to it – the label is modified automatically to reflect the new keyboard accelerator key. More info on setting different combinations of accelerator keys and modifiers can be found in the official Java documentation for <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/javax/swing/KeyStroke.html#getKeyStroke%28java.lang.String%29"><code>KeyStroke</code></a>.<br />
<center><figure style="width: 202px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Modification of menu item accelerator and tooltip" src="https://undocumentedmatlab.com/images/uimenu1.png" title="Modification of menu item accelerator and tooltip" width="202" height="200"/><figcaption class="wp-caption-text">Modification of menu item accelerator and tooltip</figcaption></figure></center><br />
Note that the Save menu-item reference can only be retrieved after opening the File menu at least once earlier; otherwise, an exception will be thrown when trying to access the menu item. The File menu does NOT need to remain open – it only needs to have been opened sometime earlier, for its menu items to be rendered. This can be done either interactively (by selecting the File menu) or programmatically:</p>
<pre lang='matlab'>
% Simulate mouse clicks to force the File main-menu to open & close
jFileMenu.doClick; % open the File menu
jFileMenu.doClick; % close the menu
% Now the Save menu is accessible:
jSave = jFileMenu.getMenuComponent(4);
</pre>
<h3 id="tooltip">Tooltip and highlight</h3>
<p>For some unknown reason, MathWorks did not include a tooltip property in its Matlab menu handle, contrary to all the other Matlab GUI components. So we must use the Java handle, specifically the <b>ToolTipText</b> property:</p>
<pre lang='matlab'>jSave.setToolTipText('modified menu item with tooltip');</pre>
<p>Java menu items also contain a property called <b>Armed</b>, which is a logical value (default=false). When turned on, the menu item is highlighted just as when it is selected (see the <i>Save As&#8230;</i> menu item in the screenshot above). On a Windows system, this means a blue background:</p>
<pre lang='matlab'>jSave.setArmed(true);</pre>
<p>When the item is actually selected and then de-selected, <b>Armed</b> reverts to a false (off) value. Alternating the <b>Armed</b> property value can achieve an effect of flashing the menu item.</p>
<h3 id="callbacks">Callbacks</h3>
<p>In addition to the standard Swing control callbacks discussed in an <a target="_blank" href="/articles/uicontrol-callbacks/">earlier article</a>, menu items possess several additional callbacks that are specific to menu items, including:</p>
<ul>
<li><b>ActionPerformedCallback</b> – fired when the menu item is invoked</li>
<li><b>StateChangedCallback</b> – fired when the menu item is selected or deselected</li>
<li><b>MenuDragMouseXXXCallback</b> (XXX=Dragged/Entered/Exited/Released) – fired when the menu item is dragged, for the corresponding event</li>
<li><b>MenuKeyXXXCallback</b> (XXX=Pressed/Released/Typed) – fired when a keyboard click event occurs (the menu item&#8217;s accelerator was typed)</li>
</ul>
<p>Using these callbacks, together with the 30-odd standard Swing callbacks, we can control our menu&#8217;s behavior to a much higher degree than possible using the standard Matlab handle.<br />
Next week, I will conclude this mini-series with an article explaining how to customize menu item icons.</ctrl></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-2">Customizing menu items part 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-3" rel="bookmark" title="Customizing menu items part 3">Customizing menu items part 3 </a> <small>Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items" rel="bookmark" title="Customizing listbox/combobox items">Customizing listbox/combobox items </a> <small>Matlab listboxes can be customized using custom Java cell-renderers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-1" rel="bookmark" title="Customizing menu items part 1">Customizing menu items part 1 </a> <small>Matlab menus can be customized in a variety of undocumented manners - first article of a series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-editboxes" rel="bookmark" title="Customizing editboxes">Customizing editboxes </a> <small>Matlab's editbox can be customized in many useful manners...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-menu-items-part-2/feed</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing menu items part 1</title>
		<link>https://undocumentedmatlab.com/articles/customizing-menu-items-part-1?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-menu-items-part-1</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-menu-items-part-1#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 25 Apr 2012 18:14:08 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Menubar]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2897</guid>

					<description><![CDATA[<p>Matlab menus can be customized in a variety of undocumented manners - first article of a series. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-1">Customizing menu items part 1</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-2" rel="bookmark" title="Customizing menu items part 2">Customizing menu items part 2 </a> <small>Matlab menu items can be customized in a variety of useful ways using their underlying Java object. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-3" rel="bookmark" title="Customizing menu items part 3">Customizing menu items part 3 </a> <small>Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items" rel="bookmark" title="Customizing listbox/combobox items">Customizing listbox/combobox items </a> <small>Matlab listboxes can be customized using custom Java cell-renderers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-uitree-nodes" rel="bookmark" title="Customizing uitree nodes &#8211; part 1">Customizing uitree nodes &#8211; part 1 </a> <small>This article describes how to customize specific nodes of Matlab GUI tree controls created using the undocumented uitree function...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Over the past years, I have not posted articles dealing with menu items. I have shown how to <a target="_blank" href="/articles/modifying-default-toolbar-menubar-actions/">directly access menu items&#8217; hidden handles</a>, but not much more than that. A year ago I <a target="_blank" href="/articles/2010-perspective/">promised</a> a mini-series on menu customizations, and it&#8217;s time to keep my promise. In today&#8217;s article, the first in the mini-series, I will present several undocumented menu customization topics that rely on pure-Matlab (i.e, no Java today). The next article in this series will focus on Java-based customizations.</p>
<h3 id="Invoking">Invoking menu item callbacks</h3>
<p>As noted above, a figure window&#8217;s menu items can be directly accessed. Once we access a menu item&#8217;s handle, we can extract its <b>Callback</b> property and directly invoke it (for example, using the semi-documented <a target="_blank" href="/articles/hgfeval/"><i><b>hgfeval</b></i> function</a>). Note that menu callbacks are kept in <b>Callback</b>, while toolbar callbacks are kept in <b>ClickedCallback</b>.<br />
Menu callbacks generally use internal <a target="_blank" href="/articles/legend-semi-documented-feature/#Semi-documented">semi-documented</a> functions (i.e., having a readable help section but no doc, online help, or official support), which are part of Matlab&#8217;s uitools folder. These functions are specific to each top-level menu tree: <i><b>filemenufcn, editmenufcn, viewmenufcn, insertmenufcn, toolsmenufcn, desktopmenufcn, winmenu</b></i>, and <i><b>helpmenufcn</b></i> implement the figure&#8217;s eight respective top-level menu trees&#8217; callbacks. These functions accept an optional figure handle (otherwise, <i><b>gcbf</b></i> is assumed), followed by a string specifying the specific menu item whose action needs to be run. <i><b>webmenufcn</b></i> implements the Help menu&#8217;s Web Resources sub-menu callbacks in a similar manner.<br />
Use of these functions makes it easy to invoke a menu action directly from our Matlab code: instead of accessing the relevant menu item and invoking its <b>Callback</b>, we simply find out the menu item string in advance and use it directly. For example,</p>
<pre lang='matlab'>
filemenufcn FileClose;
editmenufcn(hFig,'EditPaste');
</pre>
<p><i><b>uimenufcn</b></i> is a related fully-undocumented (built-in) function, available since Matlab R11 (late 1990s). It accepts a figure handle (or the zero [0] handle to indicate the desktop) and action name. For example, the fully-documented <i><b>commandwindow</b></i> function uses the following code to bring the Command Window into focus:</p>
<pre lang='matlab'>uimenufcn(0, 'WindowCommandWindow');</pre>
<h3 id="Uitools">Customizing menus via uitools</h3>
<p><i><b>makemenu</b></i> is another semi-documented uitool function that enables easy creation of hierarchical menu trees with separators and accelerators. It is a simple and effective wrapper for <i><b>uimenu</b></i>. <i><b>makemenu</b></i> is a useful function that has been made obsolete (grandfathered) without any known replacement.<br />
<i><b>makemenu</b></i> accepts four parameters: a figure handle, a char matrix of labels (&#8216;&gt;&#8217; indicating sub item, &#8216;&gt;&gt;&#8217; indicating sub-sub items etc.; &#8216;&amp;&#8217; indicating keyboard shortcut; &#8216;^x&#8217; indicating an accelerator key; &#8216;-&#8216; indicating a separator line), a char matrix of callbacks, and an optional char matrix of tags (empty by default). <i><b>makemenu</b></i> makes use of another semi-documented grandfathered function, <i><b>menulabel</b></i>, to parse the specified label components. <i><b>makemenu</b></i> returns an array of handles of the created <i><b>uimenu</b></i> items:</p>
<pre lang='matlab'>
labels = str2mat('&File', ...    % File top menu
           '>&New^n', ...           % File=>New
           '>&Open', ...            % File=>Open
           '>>Open &document^d', ...    % File=>Open=>doc
           '>>Open &graph^g', ...       % File=>Open=>graph
           '>-------', ...          % File=>separator line
           '>&Save^s', ...          % File=>Save
           '&Edit', ...		% Edit top menu
           '&View', ...		% View top menu
           '>&Axis^a', ...          % View=>Axis
           '>&Selection region^r'); % View=>Selection
calls = str2mat('', ...		% no action: File top menu
           'disp(''New'')', ...
           '', ...			% no action: Open sub-menu
           'disp(''Open doc'')', ...
           'disp(''Open graph'')', ...
           '', ...			% no action: Separator
           'disp(''Save'')', ...
           '', ...			% no action: Edit top menu
           '', ...			% no action: View top menu
           'disp(''View axis'')', ...
           'disp(''View selection region'')');
handles = makemenu(hFig, labels, calls);
set(hFig,'menuBar','none');
</pre>
<p><center><figure style="width: 267px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="A simple figure menu" src="https://undocumentedmatlab.com/images/makemenu.png" title="A simple figure menu" width="267" height="148"/><figcaption class="wp-caption-text">A simple figure menu</figcaption></figure></center></p>
<h3 id="HTML">Customizing menus via HTML</h3>
<p>Since menu items share the same <a target="_blank" href="/articles/html-support-in-matlab-uicomponents/">HTML/CSS support feature</a> as all Java Swing labels, we can specify font size/face/color, bold, italic, underline, superscript/subscript, and practically any HTML formatting.<br />
Note that some features, such as the font or foreground/background colors, have specific properties that we can set using the Java handle, instead of using HTML. The benefit of using HTML is that it enables setting all the formatting in a single property. HTML does not require using Java – just pure Matlab (see the following example).<br />
Multi-line menu items can easily be done with HTML: simply include a <code>&lt;br&gt;</code> element in the label – the menu item will split into two lines and automatically resize vertically when displayed:</p>
<pre lang='matlab'>
txt1 = '<html><b><u><i>Save</i></u>';
txt2 = '<font color="red"><sup>this file</sup></font></b></html>';
txt3 = '<br />this file as...';
set(findall(hFig,'tag','figMenuFileSave'),   'Label',[txt1,txt2]);
set(findall(hFig,'tag','figMenuFileSaveAs'), 'Label',[txt1,txt3]);
</pre>
<p><center><figure style="width: 185px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="A multi-line HTML-rendered menu item" src="https://undocumentedmatlab.com/images/uimenu2.png" title="A multi-line HTML-rendered menu item" width="185" height="184"/><figcaption class="wp-caption-text">A multi-line HTML-rendered menu item</figcaption></figure></center></p>
<pre lang='matlab'>
set(hMenuItem, 'Label',['<html>&2: C:\My Documents\doc.txt<br />'
   '<font size="-1" face="Courier New" color="red">&nbsp;&nbsp; '
   'Date: 15-Jun-2011 13:23:45<br />&nbsp;&nbsp; Size: 123 KB</font></html>']);
</pre>
<p><center><figure style="width: 411px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="HTML-rendered menu items" src="https://undocumentedmatlab.com/images/uimenu2b.png" title="HTML-rendered menu items" width="411" height="246"/><figcaption class="wp-caption-text">HTML-rendered menu items</figcaption></figure></center><br />
Much more complex customizations can be achieved using Java. So stay tuned to part 2 of this mini-series&#8230;<br />
Note: Menu customization is explored in depth in section 4.6 of my <a target="_blank" href="/matlab-java-book/">book</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-1">Customizing menu items part 1</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-2" rel="bookmark" title="Customizing menu items part 2">Customizing menu items part 2 </a> <small>Matlab menu items can be customized in a variety of useful ways using their underlying Java object. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-3" rel="bookmark" title="Customizing menu items part 3">Customizing menu items part 3 </a> <small>Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items" rel="bookmark" title="Customizing listbox/combobox items">Customizing listbox/combobox items </a> <small>Matlab listboxes can be customized using custom Java cell-renderers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-uitree-nodes" rel="bookmark" title="Customizing uitree nodes &#8211; part 1">Customizing uitree nodes &#8211; part 1 </a> <small>This article describes how to customize specific nodes of Matlab GUI tree controls created using the undocumented uitree function...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-menu-items-part-1/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>handle2struct, struct2handle &#038; Matlab 8.0</title>
		<link>https://undocumentedmatlab.com/articles/handle2struct-struct2handle-and-matlab-8?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=handle2struct-struct2handle-and-matlab-8</link>
					<comments>https://undocumentedmatlab.com/articles/handle2struct-struct2handle-and-matlab-8#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 29 Dec 2010 18:00:56 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[GUIDE]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Menubar]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Toolbar]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2023</guid>

					<description><![CDATA[<p>This article explains how we can use a couple of undocumented functions in Matlab GUI, and what we can learn from this about Matlab's future.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/handle2struct-struct2handle-and-matlab-8">handle2struct, struct2handle &amp; Matlab 8.0</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-behavior" rel="bookmark" title="Undocumented scatter plot behavior">Undocumented scatter plot behavior </a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/fig-files-format" rel="bookmark" title="FIG files format">FIG files format </a> <small>FIG files are actually MAT files in disguise. This article explains how this can be useful in Matlab applications....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-layout-managers-uicontainer-and-relatives" rel="bookmark" title="Matlab layout managers: uicontainer and relatives">Matlab layout managers: uicontainer and relatives </a> <small>Matlab contains a few undocumented GUI layout managers, which greatly facilitate handling GUI components in dynamically-changing figures....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-hg2" rel="bookmark" title="Matlab&#039;s HG2 mechanism">Matlab&#039;s HG2 mechanism </a> <small>HG2 is presumably the next generation of Matlab graphics. This article tries to explore its features....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Last week I explained that <a target="_blank" href="/articles/fig-files-format/">FIG files are simply MAT files in disguise</a>. Today, we look under the hood of Matlab&#8217;s <i><b>hgsave</b></i> function, which is used to save FIG files. We shall see that this is both useful and illuminating vis-a-vis Matlab&#8217;s future.</p>
<h3 id="handle2struct">handle2struct</h3>
<p>Under the hood, <i><b>hgsave</b></i> uses the <a target="_blank" href="/articles/legend-semi-documented-feature/#Semi-documented">semi-documented</a> built-in <i><b>handle2struct</b></i> function to convert the figure handle into a Matlab <i><b>struct</b></i> that is then stored with a simple <i><b>save</b></i> (the same function that saves MAT files) function call.<br />
The fact that <i><b>handle2struct</b></i> is semi-documented means that the function is explained in a help comment (which can be seen via the <i><b>help</b></i> command), that is nonetheless not part of the official doc sections. It is an unsupported feature originally intended only for internal Matlab use (which of course doesn&#8217;t mean we can&#8217;t use it).<br />
<i><b>handle2struct</b></i> merits a dedicated mention, since I can envision several use-cases for storing only a specific GUI handle (for example, a <i><b>uipanel</b></i>, a specific graph, or a set of GUI controls&#8217; state). In this case, all we need to do is to call <i><b>handle2struct</b></i> with the requested parent handle, then <i><b>save</b></i> the returned structure. So simple, so powerful. <i><b>handle2struct</b></i> automatically returns all the non-default property information, recursively in all the handle&#8217;s children.<br />
Note that features that are not properties of displayed handles (camera position, 3D rotation/pan/zoom states, annotations, axes-linking etc.) are not processed by <i><b>handle2struct</b></i>. For storing the states of these features, you need to use some specific handling &#8211; see the code within %matlabroot%\toolbox\matlab\graphics\private\hgsaveStructDbl.m for details. Basically, hgsaveStructDbl.m reads the state of all these features and temporarily stores them in the base handle&#8217;s <strong>ApplicationData</strong> property; <i><b>handle2struct</b></i> then reads them as any other regular handle property data, and then hgsaveStructDbl.m clears the temporary data from the handle&#8217;s <strong>ApplicationData</strong>. We can use the same trick for any other application state, of course.</p>
<h3 id="struct2handle">struct2handle</h3>
<p><i><b>handle2struct</b></i> has a reverse function &#8211; the semi-documented <i><b>struct2handle</b></i>. I use it for creating dynamic preference panels: As in Matlab&#8217;s Preferences window, I have a list of preference topics and a set of corresponding options panels. In my case, it was easy to design each panel as a separate FIG file using GUIDE. In run-time, I simply load the relevant panel from its FIG file as described above, and place it onscreen in a dedicated <i><b>uipanel</b></i> using <i><b>struct2handle</b></i>. This enables very easy maintenance of preference panels, without sacrificing any functionality.<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Matlab's preferences panels" src="https://undocumentedmatlab.com/images/FIG_MAT.png" title="Matlab's preferences panels" width="450" height="274" /><figcaption class="wp-caption-text">Matlab's preferences panels</figcaption></figure></center><br />
Figure menus and toolbars are not normally stored by <i><b>hgsave</b></i>, unless you use the optional &#8216;all&#8217; parameter (and correspondingly in <i><b>hgload</b></i>, if you choose to use it). <i><b>handle2struct</b></i> and <i><b>handle2struct</b></i> accept the same optional &#8216;all&#8217; parameter as <i><b>hgsave</b></i> and <i><b>hgload</b></i>. Unfortunately, a warning message indicates that this option will be discontinued in some future Matlab version.<br />
Which brings us to our final topic for today:</p>
<h3 id="Matlab8">Matlab 8: Boldly going where no FIG has gone before&#8230;</h3>
<p>Remember my post earlier this year about the <a target="_blank" href="/articles/matlab-hg2/">new HG2 mechanism</a>? I speculated that when MathWorks decides to release HG2, it will define this as a major Matlab release and label it Matlab 8.0.<br />
The source code in hgsave.m appears to confirm my speculation. Here is the relevant code section (slightly edited for clarity), which speaks for itself:</p>
<pre lang="matlab">
% Decide which save code path to use
if ~feature('HGUsingMatlabClasses')   % <== existing HG
    % Warn if user passed in 'all' flag
    if SaveAll
        warning( 'MATLAB:hgsave:DeprecatedOption', ...
            'The ''all'' option to hgsave will be removed in a future release.');
    end
    hgS = hgsaveStructDbl(h, SaveAll);
    SaveVer = '070000';
    SaveOldFig = true;
else   % <== HG2
    % Warn if user passed in 'all' flag
    if SaveAll
        warning( 'MATLAB:hgsave:DeprecatedOption', ...
            'The ''all'' option to hgsave has been removed.');
    end
    if SaveOldFig
        hgS = hgsaveStructClass(h);
        SaveVer = '080000';
    else
        hgO = hgsaveObject(h);
        SaveVer = '080000';
    end
end
% Revision encoded as 2 digits for major revision,
% 2 digits for minor revision, and 2 digits for
% patch revision.  This is the minimum revision
% required to fully support the file format.
% e.g. 070000 means 7.0.0
</pre>
<p>As can be seen, when Matlab starts using HG2 (perhaps in 2011?), the top-level structure node will be called "hgS_080000", indicating Matlab 8.0. QED.<br />
As a side-note, note that in HG2/Matlab8, although the comment about using 'all' indicates that it has been removed, in practice it is still accepted (although not being used). This will enable your code to be backward-compatible whenever HG2 launches, and future-compatible today.<br />
Have you used <i><b>handle2struct</b></i> or <i><b>struct2handle</b></i>? If so, please share your experience in a <a href="/articles/handle2struct-struct2handle-and-matlab-8/#respond">comment</a>.<br />
<em>Let the upcoming 2011 be a year filled with revelations, announcements and fulfillment! Happy New Year everybody!</em></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/handle2struct-struct2handle-and-matlab-8">handle2struct, struct2handle &amp; Matlab 8.0</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-behavior" rel="bookmark" title="Undocumented scatter plot behavior">Undocumented scatter plot behavior </a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/fig-files-format" rel="bookmark" title="FIG files format">FIG files format </a> <small>FIG files are actually MAT files in disguise. This article explains how this can be useful in Matlab applications....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-layout-managers-uicontainer-and-relatives" rel="bookmark" title="Matlab layout managers: uicontainer and relatives">Matlab layout managers: uicontainer and relatives </a> <small>Matlab contains a few undocumented GUI layout managers, which greatly facilitate handling GUI components in dynamically-changing figures....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-hg2" rel="bookmark" title="Matlab&#039;s HG2 mechanism">Matlab&#039;s HG2 mechanism </a> <small>HG2 is presumably the next generation of Matlab graphics. This article tries to explore its features....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/handle2struct-struct2handle-and-matlab-8/feed</wfw:commentRss>
			<slash:comments>11</slash:comments>
		
		
			</item>
		<item>
		<title>Accessing plot brushed data</title>
		<link>https://undocumentedmatlab.com/articles/accessing-plot-brushed-data?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=accessing-plot-brushed-data</link>
					<comments>https://undocumentedmatlab.com/articles/accessing-plot-brushed-data#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 06 Oct 2010 18:00:45 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[Menubar]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[scribe]]></category>
		<category><![CDATA[UIInspect]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=1911</guid>

					<description><![CDATA[<p>Plot data brushing can be accessed programmatically using very simple pure-Matlab code</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/accessing-plot-brushed-data">Accessing plot brushed data</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/hidden-hg2-plot-functionality" rel="bookmark" title="Accessing hidden HG2 plot functionality">Accessing hidden HG2 plot functionality </a> <small>In HG2, some of the plot functionality is hidden in undocumented properties. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/draggable-plot-data-tips" rel="bookmark" title="Draggable plot data-tips">Draggable plot data-tips </a> <small>Matlab's standard plot data-tips can be customized to enable dragging, without being limitted to be adjacent to their data-point. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/controlling-plot-data-tips" rel="bookmark" title="Controlling plot data-tips">Controlling plot data-tips </a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-liminclude-properties" rel="bookmark" title="Plot LimInclude properties">Plot LimInclude properties </a> <small>The plot objects' XLimInclude, YLimInclude, ZLimInclude, ALimInclude and CLimInclude properties are an important feature, that has both functional and performance implications....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A few days ago, a reader of the Matlab Desktop blog <a target="_blank" rel="nofollow" href="http://blogs.mathworks.com/desktop/2008/05/12/brush-up-on-your-data/#comment-7364">asked</a> whether it is possible to store plot brushed data in a separate variable for later processing. <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/data_analysis/brh7_p3-1.html#brh7_p3-3">Data Brushing</a>, first introduced in R2008a, enables interactive selection and marking of plot data points. The brushed data can then be stored in a variable using the context (right-click) menu, or the figure&#8217;s Tools/Brushing menu.<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Saving brushed data to a variable" src="https://undocumentedmatlab.com/images/Brushing1b.png" title="Saving brushed data to a variable" width="450" height="325" /><figcaption class="wp-caption-text">Saving brushed data to a variable</figcaption></figure></center><br />
The said reader has specifically wanted programmatic access, rather than interactivity. The official answer is that data brushing was designed to be an interactive tool, and so this cannot be done. However, this has never stopped us before. So off I went to launch my favorite inspection tool, the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect-display-methods-properties-callbacks-of-an-object">UIInspect utility</a> on the figure above (UIInspect will be described in a near-future article), which can be recreated with the following simple code:</p>
<pre lang="matlab">
t=0:0.2:25; plot(t,sin(t),'.-');
% Now brush some data points...
uiinspect(gca);
</pre>
<p><center><figure style="width: 450px" class="wp-caption aligncenter"><a target="_blank" href="/images/Brushing2a.png"><img loading="lazy" decoding="async" alt="UIInspect-ion of a data-brushed plot" src="https://undocumentedmatlab.com/images/Brushing2a.png" title="UIInspect-ion of a data-brushed plot" width="450" height="389" /></a><figcaption class="wp-caption-text">UIInspect-ion of a data-brushed plot (click for details)</figcaption></figure></center><br />
A couple of alternative answers to the reader&#8217;s question were immediately apparent:</p>
<h3 id="data">Directly accessing brushed data</h3>
<p>First, we notice that data brushing added data-brushing context menus, both of which are called <i>BrushSeriesContextMenu</i> (the duplication is an internal Matlab bug, that does not affect usability as far as I can tell).<br />
Also, an invisible scribe overlay axes has been added to hold the new annotations (data brushing is considered an annotation; scribe axes deserve a separate article, which they will indeed get someday).<br />
More importantly for our needs, we see a new <i><b>line</b></i> item called &#8216;Brushing&#8217;, which displays the red lines and data points that we seek. We can now easily get the brushed data using this line&#8217;s <b>XData</b> and <b>YData</b> properties: <u>non</u>-brushed data points simply have NaN values:<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="UIInspect-ion of the data-brushing line" src="https://undocumentedmatlab.com/images/Brushing2b.png" title="UIInspect-ion of the data-brushing line" width="450" height="325" /><figcaption class="wp-caption-text">UIInspect-ion of the data-brushing line</figcaption></figure></center></p>
<pre lang="matlab">
hBrushLine = findall(gca,'tag','Brushing');
brushedData = get(hBrushLine, {'Xdata','Ydata'});
brushedIdx = ~isnan(brushedData{1});
brushedXData = brushedData{1}(brushedIdx);
brushedYData = brushedData{2}(brushedIdx);
% and similarly for ZData in 3D plots
</pre>
<h3 id="callbacks">Accessing brushing callbacks</h3>
<p>Yet another way of approaching the problem is to use the available callback functions built-into the data-brushing functionality. We can access either the <i>BrushSeriesContextMenu</i> or the figure&#8217;s Tools/Brushing menu. I will leave the former (context-menu) approach as an exercise to the reader, and just describe the figure&#8217;s menu approach.<br />
As I have already explained in a <a target="_blank" href="/articles/modifying-default-toolbar-menubar-actions/">dedicated article</a>, figure menu-bar actions are accessible via their handles, and we can retrieve that using a unique tag (well, most of the time &#8211; read that article for details). In our case, the Tools/Brushing/Create-new-variable menu item has the unique tag &#8216;figDataManagerNewVar&#8217;. So let&#8217;s use it:</p>
<pre lang="matlab">
>> hNewVarMenuItem = findall(gcf,'tag','figDataManagerNewVar')
hNewVarMenuItem =
          742.000244140625
>> hNewVarCallback = get(hNewVarMenuItem,'callback')
hNewVarCallback =
    @datamanager.newvar
>> hNewVarCallback(gcf)   % activate the callback
% => set 'ans' as the new variable holding the brushed data
>> ans
ans =
                       6.4         0.116549204850494
                       6.6         0.311541363513379
                       6.8         0.494113351138609
                         7         0.656986598718789
                       7.2         0.793667863849153
                       7.4         0.898708095811627
                       7.6         0.967919672031486
                       7.8         0.998543345374605
                       ...         ...
</pre>
<p>Of course, we could also have gone the hard way, via the scribe axes and the annotations route. For masochistic people like me it could even be a worthwhile challenge. But for all other normal people, why bother when there are such simple alternatives, if we only knew how to find them. 🙂</p>
<h3 id="hg2">Updates for HG2 (R2014b+)</h3>
<p>In HG2 (R2014b+), <code>findall(gca,'tag','Brushing')</code> returns empty data since the way that brushed data is stored has changed. You can access the brushing data using the plot line&#8217;s hidden <b>BrushHandles</b> property, as follows:</p>
<pre lang='matlab'>
hLine = plot(...);
hBrushHandles = hLine.BrushHandles;
hBrushChildrenHandles = hBrushHandles.Children;  % Marker, LineStrip
</pre>
<p>I described the new <code>Marker</code> objects <a href="/articles/plot-markers-transparency-and-color-gradient" target="_blank">here</a>, and <code>LineStrip</code> objects <a href="/articles/customizing-axes-rulers#Axle" target="_blank">here</a>. The brushed vertex data can be retrieved from either of them. For example:</p>
<pre lang='matlab'>
>> hBrushChildrenHandles(1).VertextData
ans =
     1     2     3     4   % X-data of 4 data points
     1     2     3     4   % Y-data of 4 data points
     0     0     0     0   % Z-data of 4 data points
</pre>
<p>If you only need the brushed data points (not the handles for the <code>Markers</code> and <code>LineStrip</code>, you can get them directly from the line handle, using the hidden <b>BrushData</b> property:</p>
<pre lang='matlab'>
>> brushedIdx = logical(hLine.BrushData);  % logical array
>> brushedXData = hLine.XData(brushedIdx);
>> brushedYData = hLine.YData(brushedIdx)
brushedYData =
     1     2     3     4
</pre>
<p><b><u>Addendum 28 Feb, 2018:</u></b> MathWorks posted an official post on Matlab Answers that references the BrushData functionality &#8211; <a href="https://www.mathworks.com/matlabcentral/answers/385226-how-to-use-the-data-brush-tool-to-automatically-save-selected-points-in-multiple-line-plots" rel="nofollow" target="_blank">see here</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/accessing-plot-brushed-data">Accessing plot brushed data</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/hidden-hg2-plot-functionality" rel="bookmark" title="Accessing hidden HG2 plot functionality">Accessing hidden HG2 plot functionality </a> <small>In HG2, some of the plot functionality is hidden in undocumented properties. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/draggable-plot-data-tips" rel="bookmark" title="Draggable plot data-tips">Draggable plot data-tips </a> <small>Matlab's standard plot data-tips can be customized to enable dragging, without being limitted to be adjacent to their data-point. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/controlling-plot-data-tips" rel="bookmark" title="Controlling plot data-tips">Controlling plot data-tips </a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-liminclude-properties" rel="bookmark" title="Plot LimInclude properties">Plot LimInclude properties </a> <small>The plot objects' XLimInclude, YLimInclude, ZLimInclude, ALimInclude and CLimInclude properties are an important feature, that has both functional and performance implications....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/accessing-plot-brushed-data/feed</wfw:commentRss>
			<slash:comments>25</slash:comments>
		
		
			</item>
		<item>
		<title>Modifying default toolbar/menubar actions</title>
		<link>https://undocumentedmatlab.com/articles/modifying-default-toolbar-menubar-actions?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=modifying-default-toolbar-menubar-actions</link>
					<comments>https://undocumentedmatlab.com/articles/modifying-default-toolbar-menubar-actions#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 02 Jun 2010 14:08:19 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Menubar]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Toolbar]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=1430</guid>

					<description><![CDATA[<p>The default Matlab figure toolbar and menu actions can easily be modified using simple pure-Matlab code. This article explains how.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/modifying-default-toolbar-menubar-actions">Modifying default toolbar/menubar actions</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-standard-figure-toolbar-menubar" rel="bookmark" title="Customizing the standard figure toolbar, menubar">Customizing the standard figure toolbar, menubar </a> <small>The standard figure toolbar and menubar can easily be modified to include a list of recently-used files....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/toolbar-button-labels" rel="bookmark" title="Toolbar button labels">Toolbar button labels </a> <small>GUI toolbar button labels can easily be set and customized using underlying Java components. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/getting-default-hg-property-values" rel="bookmark" title="Getting default HG property values">Getting default HG property values </a> <small>Matlab has documented how to modify default property values, but not how to get the full list of current defaults. This article explains how to do this. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Did you ever wish to modify Matlab&#8217;s default toolbar/menubar items?<br />
I recently consulted to a client who needed to modify the default behavior of the <i><b>legend</b></i> action in the toolbar, and the corresponding item on the main menu (Insert / Legend). The official version is that only user-added items can be customized, whereas standard Matlab items cannot.<br />
Luckily, this can indeed be done using simple pure-Matlab code. The trick is to get the handles of the toolbar/menubar objects and then to modify their callback properties.<br />
<center><figure style="width: 463px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Default legend insertion action" src="https://undocumentedmatlab.com/images/Toolbar_Menubar_actions1.png" title="Default legend insertion action" width="463" height="265" /><figcaption class="wp-caption-text">Default legend insertion action</figcaption></figure></center></p>
<h3 id="Item-handles">Using the toolbar/menubar item handles</h3>
<p>Getting the handles can be done in several different ways. In my experience, using the object&#8217;s tag string is often easiest, fastest and more maintainable. Note that the Matlab toolbar and main menu handles are normally hidden (<b>HandleVisibility</b> = &#8216;off&#8217;). Therefore, in order to access them we need to use the <i><b>findall</b></i> function rather than the better-known <i><b>findobj</b></i> function. Also note that to set the callbacks we need to access differently-named properties: <b>ClickedCallback</b> for toolbar buttons, and <b>Callback</b> for menu items:</p>
<pre lang="matlab">
hToolLegend = findall(gcf,'tag','Annotation.InsertLegend');
set(hToolLegend, 'ClickedCallback',{@cbLegend,hFig,myData});
hMenuLegend = findall(gcf,'tag','figMenuInsertLegend');
set(hMenuLegend, 'Callback',{@cbLegend,hFig,myData});
</pre>
<p>As a side note, two undocumented/unsupported functions,  <i><b>uitool</b>(hFig,tagName)</i> and <i><b>uigettoolbar</b></i>, also retrieve toolbar items. Since using <i><b>findall</b></i> is so simple and more supported, I suggest using the <i><b>findall</b></i> approach.<br />
To see the list of available toolbar/menubar tags, use the following code snippet:</p>
<pre lang="matlab">
% Toolbar tag names:
>> hToolbar = findall(gcf,'tag','FigureToolBar');
>> get(findall(hToolbar),'tag')
ans =
    'FigureToolBar'
    'Plottools.PlottoolsOn'
    'Plottools.PlottoolsOff'
    'Annotation.InsertLegend'
    'Annotation.InsertColorbar'
    'DataManager.Linking'
    'Exploration.Brushing'
    'Exploration.DataCursor'
    'Exploration.Rotate'
    'Exploration.Pan'
    'Exploration.ZoomOut'
    'Exploration.ZoomIn'
    'Standard.EditPlot'
    'Standard.PrintFigure'
    'Standard.SaveFigure'
    'Standard.FileOpen'
    'Standard.NewFigure'
    ''
% Menu-bar tag names:
>> get(findall(gcf,'type','uimenu'),'tag')
ans =
    'figMenuHelp'
    'figMenuWindow'
    'figMenuDesktop'
    'figMenuTools'
    'figMenuInsert'
    'figMenuView'
    'figMenuEdit'
    'figMenuFile'
    'figMenuHelpAbout'
    'figMenuHelpPatens'
    'figMenuHelpTerms'
    'figMenuHelpActivation'
    'figMenuDemos'
    'figMenuTutorials'
    'figMenuHelpUpdates'
    'figMenuGetTrials'
    'figMenuWeb'
    'figMenuHelpPrintingExport'
    'figMenuHelpAnnotatingGraphs'
    'figMenuHelpPlottingTools'
    'figMenuHelpGraphics'
    ''
    ''                    < = Note the missing tag names...
    ''
    'figMenuToolsBFDS'    <= note the duplicate tag names...
    'figMenuToolsBFDS'
    'figDataManagerBrushTools'
    'figMenuToolsAlign'
    'figMenuToolsAlign'
    ... (plus many many more...)
</pre>
<p>Unfortunately, as seen above, Matlab developers forgot to assign tags to some default toolbar/menubar items. Luckily, in my particular case, both legend handles (toolbar, menu) have valid tag names that can be used: 'Annotation.InsertLegend' and 'figMenuInsertLegend'.<br />
If an item's tag is missing, you can always find its handle using its <b>Parent</b>, <b>Label</b>, <b>Tooltip</b> or <b>Callback</b> properties. For example:</p>
<pre lang="matlab">hPrintMenuItem = get(findall(gcf,'Label','&Print...'));</pre>
<p>Note that property values, such as the tag names or labels, are unsupported and undocumented. They may change without warning or notice between Matlab releases, and have indeed done so in the past. Therefore, if your code needs to be compatible with older Matlab releases, ensure that you cover all the possible property values, or use a different way to access the handles. While <u>using</u> the tag name or label as shown above is considered &#8220;Low risk&#8221; (I don&#8217;t expect it to break in the near future), their actual <u>values</u> should be considered somewhat more risky and we should therefore code defensively.</p>
<h3 id="Print">Another simple example: Print Preview</h3>
<p>As another simple and very useful example, let&#8217;s modify the default Print action (and tooltip) on the figure toolbar to display the Print-Preview window rather than send the figure directly to the printer:<br />
<center><figure style="width: 463px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Matlab's default toolbar Print action" src="https://undocumentedmatlab.com/images/Toolbar_Menubar_actions2b.png" title="Matlab's default toolbar Print action" width="463" height="108" /><figcaption class="wp-caption-text">Matlab's default toolbar Print action</figcaption></figure></center></p>
<pre lang="matlab">
hToolbar = findall(gcf,'tag','FigureToolBar');
hPrintButton = findall(hToolbar,'tag','Standard.PrintFigure');
set(hPrintButton, 'ClickedCallback','printpreview(gcbf)', 'TooltipString','Print Preview');
</pre>
<p><center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Matlab's Print Preview window" src="https://undocumentedmatlab.com/images/PrintPreview.png" title="Matlab's Print Preview window" width="450" height="418" /><figcaption class="wp-caption-text">Matlab's Print Preview window</figcaption></figure></center><br />
More advanced customization of the toolbar and menu items are possible, but require a bit of Java code. Examples of toolbar customizations were presented in past articles (<a target="_blank" href="/articles/figure-toolbar-components/">here</a> and <a target="_blank" href="/articles/figure-toolbar-customizations/">here</a>). A future article will explain how to customize menu items.<br />
Have you found a nifty way to customize the menubar or toolbar? If so, please share it in the <a href="#respond">comments section</a> below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/modifying-default-toolbar-menubar-actions">Modifying default toolbar/menubar actions</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-standard-figure-toolbar-menubar" rel="bookmark" title="Customizing the standard figure toolbar, menubar">Customizing the standard figure toolbar, menubar </a> <small>The standard figure toolbar and menubar can easily be modified to include a list of recently-used files....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/toolbar-button-labels" rel="bookmark" title="Toolbar button labels">Toolbar button labels </a> <small>GUI toolbar button labels can easily be set and customized using underlying Java components. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/getting-default-hg-property-values" rel="bookmark" title="Getting default HG property values">Getting default HG property values </a> <small>Matlab has documented how to modify default property values, but not how to get the full list of current defaults. This article explains how to do this. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/modifying-default-toolbar-menubar-actions/feed</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing uiundo</title>
		<link>https://undocumentedmatlab.com/articles/customizing-uiundo?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-uiundo</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-uiundo#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 05 Nov 2009 00:29:13 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Menubar]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[uitools]]></category>
		<category><![CDATA[uiundo]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=708</guid>

					<description><![CDATA[<p>This article describes how Matlab's undocumented uiundo undo/redo manager can be customized</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-uiundo">Customizing uiundo</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/uiundo-matlab-undocumented-undo-redo-manager" rel="bookmark" title="uiundo &#8211; Matlab&#039;s undocumented undo/redo manager">uiundo &#8211; Matlab&#039;s undocumented undo/redo manager </a> <small>The built-in uiundo function provides easy yet undocumented access to Matlab's powerful undo/redo functionality. This article explains its usage....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uisplittool-uitogglesplittool-callbacks" rel="bookmark" title="uisplittool &amp; uitogglesplittool callbacks">uisplittool &amp; uitogglesplittool callbacks </a> <small>Matlab's undocumented uisplittool and uitogglesplittool are powerful toolbar controls - this article explains how to customize their behavior...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-print-setup" rel="bookmark" title="Customizing print setup">Customizing print setup </a> <small>Matlab figures print-setup can be customized to automatically prepare the figure for printing in a specific configuration...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Last week I discussed <a target="_blank" href="/articles/uiundo-matlab-undocumented-undo-redo-manager/"><b><i>uiundo</i></b> &#8211; Matlab&#8217;s undocumented undo/redo manager</a>. Today, I will show how this object can be customized for some specific needs. However, we first need to understand a little more about how <b><i>uiundo</i></b> works beneath the hood.<br />
Matlab stores all of a figure&#8217;s undo/redo data in a hidden figure object, referenced by <b><i>getappdata</i></b>(hFig,&#8217;uitools_FigureToolManager&#8217;). This means that by default <b><i>uiundo</i></b> works at the figure level, rather than the application level or the GUI component level. If we wish to modify this default behavior, we need to programmatically inspect and filter the undo/redo actions stack based on the action source. Read below to see how this can be done.<br />
The hidden <i>uitools_FigureToolManager</i> object, defined in %MATLABROOT%\toolbox\matlab\uitools\@uiundo\, uses a stack to store instances of the undo/redo <i>cmd</i> data structure introduced in last week&#8217;s post:</p>
<pre lang="matlab">
% Retrieve redo/undo object
undoObj = getappdata(hFig,'uitools_FigureToolManager');
if isempty(undoObj)
   try
      % R2014a and earlier
      undoObj = uitools.FigureToolManager(hFig);
   catch
      % R2014b and newer
      undoObj = matlab.uitools.internal.FigureToolManager(hFig);
   end
   setappdata(hFig,'uitools_FigureToolManager',undoObj);
end
>> get(undoObj)
    CommandManager: [1x1 uiundo.CommandManager]
            Figure: [1x1 figure]
        UndoUIMenu: [1x1 uimenu]
        RedoUIMenu: [1x1 uimenu]
</pre>
<p>There are several interesting things we can do with this undoObj. First, let&#8217;s modify the main-menu items (I will discuss menu customization in more detail in another post):</p>
<pre lang="matlab">
% Modify the main menu item (similarly for redo/undo)
if ~isempty(undoObj.RedoUIMenu)
   undoObj.RedoUIMenu.Position =1; %default=2 (undo above redo)
   undoObj.RedoUIMenu.Enable = 'off';     % default='on'
   undoObj.RedoUIMenu.Checked = 'on';     % default='off'
   undoObj.RedoUIMenu.ForegroundColor = [1,0,0];  % =red
end
if ~isempty(undoObj.UndoUIMenu)
   undoObj.UndoUIMenu.Label = '<html><b><i>Undo action';
   % Note: &Undo underlines 'U' and adds a keyboard accelerator
   % but unfortunately only if the label is non-HTML ...
   undoObj.UndoUIMenu.Separator = 'on';   % default='off'
   undoObj.UndoUIMenu.Checked = 'on';     % default='off'
   undoObj.UndoUIMenu.ForegroundColor = 'blue'; % default=black
end
</i></b></html></pre>
<p><center><figure style="width: 284px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Menu before customization" src="https://undocumentedmatlab.com/images/uiundo2a.png" title="Menu before customization" width="284" height="166" /></p>
<p>
<img loading="lazy" decoding="async" alt="Menu after customization" src="https://undocumentedmatlab.com/images/uiundo3a.png" title="Menu after customization" width="284" height="166" /><figcaption class="wp-caption-text">Figure menu before and after customization</figcaption></figure></p>
<p></center><br />
Now, let&#8217;s take a look at undoObj&#8217;s <i>CommandManager</i> child (the <i>Figure</i> child object is simply <i><b>handle</b>(hFig)</i>, and so is not very interesting):</p>
<pre lang="matlab">
>> undoObj.CommandManager.get
             UndoStack: [13x1 uiundo.FunctionCommand]
             RedoStack: [1x1 uiundo.FunctionCommand]
    MaxUndoStackLength: []
               Verbose: []
>> undoObj.CommandManager.UndoStack(end).get
             Parent: []
       MCodeComment: []
               Name: 'slider update (0.48 to 0.38)'
           Function: @internal_update
           Varargin: {[53.0037841796875]  [0.38]  [1x1 double]}
    InverseFunction: @internal_update
    InverseVarargin: {[53.0037841796875]  [0.48]  [1x1 double]}
</pre>
<p>This looks familiar: In fact, it is exactly the <i>cmd</i> data structure being passed to the <b><i>uiundo</i></b> function, with the additional (apparently unused) properties <i>Parent</i> and <i>MCodeComment</i>. <i>CommandManager</i>&#8216;s <i>UndoStack</i> and <i>RedoStack</i> child objects contain all stored undo/redo actions such that the latest action is at the end of these arrays. In the snippet above, there are 13 undo-able actions, with the latest action in <i>UndoStack(end)</i>. <i>UndoStack</i> and <i>RedoStack</i> have the same structure:</p>
<ul>
<li><i>Name</i> contains the action description (presented in the figure&#8217;s menu)</li>
<li><i>Function</i> is the function handle that will be invoked if the action is <b>re</b>done</li>
<li><i>Varargin</i> are the arguments passed to <i>Function</i> during redo</li>
<li><i>InverseFunction</i> is the function handle that will be invoked if the action is <b>un</b>done</li>
<li><i>InverseVarargin</i> are the arguments passed to <i>InverseFunction</i> during undo</li>
<li><i>Parent</i> and <i>MCodeComment</i> &#8211; I could not determine what these are used for
</li>
</ul>
<p>We can inspect the latest undo/redo actions, without activating them, by using <i>CommandManager</i>&#8216;s <i>peekundo()</i> and <i>peekredo()</i> methods (which return empty [] if no undo/redo action is available):</p>
<pre lang="matlab">
>> undoObj.CommandManager.peekredo.get % first check if isempty
             Parent: []
       MCodeComment: []
               Name: 'slider update (0.38 to 0.28)'
           Function: @internal_update
           Varargin: {[53.0037841796875]  [0.28]  [1x1 double]}
    InverseFunction: @internal_update
    InverseVarargin: {[53.0037841796875]  [0.38]  [1x1 double]}
>> undoObj.CommandManager.peekundo.get
             Parent: []
       MCodeComment: []
               Name: 'slider update (0.48 to 0.38)'
           Function: @internal_update
           Varargin: {[53.0037841796875]  [0.38]  [1x1 double]}
    InverseFunction: @internal_update
    InverseVarargin: {[53.0037841796875]  [0.48]  [1x1 double]}
>> undoObj.CommandManager.peekundo.Name
ans =
slider update (0.48 to 0.38)
</pre>
<p>We can undo/redo the latest action (last element of the <i>UndoStack</i>/<i>RedoStack</i>) by invoking <i>CommandManager</i>&#8216;s <i>undo()</i>/<i>redo()</i> methods. This is actually what <b><i>uiundo</i></b> is doing behind the scenes when it is called with the &#8216;execUndo&#8217; and &#8216;execRedo&#8217; arguments:</p>
<pre lang="matlab">
undoObj.CommandManager.undo;
undoObj.CommandManager.redo;
</pre>
<p>We can clear the entire actions stack by using <i>CommandManager</i>&#8216;s <i>empty()</i> method. This can be useful, for example, after a &#8216;Save&#8217; or &#8216;Apply&#8217; operation in our GUI:</p>
<pre lang="matlab">
undoObj.CommandManager.empty;
</pre>
<p>If we set <i>CommandManager</i>&#8216;s <i>Verbose</i> property to any non-empty value, debug information is spilled onto the Command Window when new <b><i>uiundo</i></b> actions are added:</p>
<pre lang="matlab">
>> undoObj.CommandManager.Verbose = 1;
% now move the slider and see the debug info below:
internal_update(h_uicontrol, [0.48,], h_uicontrol); % Called by slider update (0.28 to 0.48)
internal_update(h_uicontrol, [0.58,], h_uicontrol); % Called by slider update (0.48 to 0.58)
</pre>
<p>Finally, <i>CommandManager</i> uses its <i>MaxUndoStackLength</i> property to limit the size of the undo/redo stacks. This property is defined as read-only in %matlabroot%\toolbox\matlab\uitools\@uiundo\@CommandManager\schema.m line #12, so if you wish to programmatically modify this property from its default value of empty (=unlimited), you will need to comment out that line.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-uiundo">Customizing uiundo</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/uiundo-matlab-undocumented-undo-redo-manager" rel="bookmark" title="uiundo &#8211; Matlab&#039;s undocumented undo/redo manager">uiundo &#8211; Matlab&#039;s undocumented undo/redo manager </a> <small>The built-in uiundo function provides easy yet undocumented access to Matlab's powerful undo/redo functionality. This article explains its usage....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uisplittool-uitogglesplittool-callbacks" rel="bookmark" title="uisplittool &amp; uitogglesplittool callbacks">uisplittool &amp; uitogglesplittool callbacks </a> <small>Matlab's undocumented uisplittool and uitogglesplittool are powerful toolbar controls - this article explains how to customize their behavior...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-print-setup" rel="bookmark" title="Customizing print setup">Customizing print setup </a> <small>Matlab figures print-setup can be customized to automatically prepare the figure for printing in a specific configuration...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-uiundo/feed</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
	</channel>
</rss>
