<?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>Undocumented Matlab &#187; Callbacks</title> <atom:link href="http://undocumentedmatlab.com/blog/tag/callbacks/feed/" rel="self" type="application/rss+xml" /><link>http://undocumentedmatlab.com</link> <description>Charting Matlab's unsupported hidden underbelly</description> <lastBuildDate>Thu, 17 May 2012 12:01:26 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.1.1</generator> <item><title>Customizing menu items part 2</title><link>http://undocumentedmatlab.com/blog/customizing-menu-items-part-2/</link> <comments>http://undocumentedmatlab.com/blog/customizing-menu-items-part-2/#comments</comments> <pubDate>Wed, 02 May 2012 11:57:38 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <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[Matlab menu items can be customized in a variety of useful ways using their underlying Java object.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/customizing-workspace-context-menu/' rel='bookmark' title='Customizing Workspace context-menu'>Customizing Workspace context-menu</a> <small>Matlab's Workspace table context-menu can be configured with user-defined actions - this article explains how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/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><pre> </pre>]]></description> <content:encoded><![CDATA[<p>Last week I <a
target="_blank" href="http://undocumentedmatlab.com/blog/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="http://undocumentedmatlab.com/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.</p><p>Getting the Java reference for the figure window&#8217;s main menu is very easy:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jFrame = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span>hFig<span style="color: #080;">&#41;</span>,<span style="color:#A020F0;">'JavaFrame'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">try</span>
    <span style="color: #228B22;">% R2008a and later</span>
    jMenuBar = jFrame.<span style="">fHG1Client</span>.<span style="">getMenuBar</span>;
<span style="color: #0000FF;">catch</span>
    <span style="color: #228B22;">% R2007b and earlier</span>
    jMenuBar = jFrame.<span style="">fFigureClient</span>.<span style="">getMenuBar</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>Note that we have used the figure handle&#8217;s hidden <a
target="_blank" href="http://undocumentedmatlab.com/blog/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.</p><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>. 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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">for</span> menuIdx = <span style="color: #33f;">1</span> <span style="color: #F0F;">:</span> jMenuBar.<span style="">getComponentCount</span>
    jMenu = jMenuBar.<span style="">getComponent</span><span style="color: #080;">&#40;</span>menuIdx-<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
    hjMenu = handle<span style="color: #080;">&#40;</span>jMenu,<span style="color:#A020F0;">'CallbackProperties'</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hjMenu,<span style="color:#A020F0;">'MouseEnteredCallback'</span>,<span style="color:#A020F0;">'doClick(gcbo)'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% File main menu is the first main menu item =&gt; index=0</span>
jFileMenu = jMenuBar.<span style="">getComponent</span><span style="color: #080;">&#40;</span><span style="color: #33f;">0</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Save menu item is the 5th menu item (separators included)</span>
jSave = jFileMenu.<span style="">getMenuComponent</span><span style="color: #080;">&#40;</span><span style="color: #33f;">4</span><span style="color: #080;">&#41;</span>; <span style="color: #228B22;">%Java indexes start with 0!</span>
inspect<span style="color: #080;">&#40;</span>jSave<span style="color: #080;">&#41;</span> 	<span style="color: #228B22;">% just to be sure: label='Save' =&gt; good!</span>
&nbsp;
<span style="color: #228B22;">% Finally, set a new accelerator key for this menu item:</span>
jAccelerator = javax.<span style="">swing</span>.<span style="">KeyStroke</span>.<span style="">getKeyStroke</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'alt shift S'</span><span style="color: #080;">&#41;</span>;
jSave.<span style="">setAccelerator</span><span style="color: #080;">&#40;</span>jAccelerator<span style="color: #080;">&#41;</span>;</pre></div></div><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>.</p><p><center><div
class="wp-caption aligncenter" style="width: 212px"><img
alt="Modification of menu item accelerator and tooltip" src="http://UndocumentedMatlab.com/images/uimenu1.png" title="Modification of menu item accelerator and tooltip" width="202" height="200"/><p
class="wp-caption-text">Modification of menu item accelerator and tooltip</p></div></center></p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Simulate mouse clicks to force the File main-menu to open &amp; close</span>
jFileMenu.<span style="">doClick</span>; <span style="color: #228B22;">% open the File menu</span>
jFileMenu.<span style="">doClick</span>; <span style="color: #228B22;">% close the menu</span>
&nbsp;
<span style="color: #228B22;">% Now the Save menu is accessible:</span>
jSave = jFileMenu.<span style="">getMenuComponent</span><span style="color: #080;">&#40;</span><span style="color: #33f;">4</span><span style="color: #080;">&#41;</span>;</pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jSave.<span style="">setToolTipText</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'modified menu item with tooltip'</span><span style="color: #080;">&#41;</span>;</pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jSave.<span style="">setArmed</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">true</span><span style="color: #080;">&#41;</span>;</pre></div></div><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="http://undocumentedmatlab.com/blog/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.</p><p>Next week, I will conclude this mini-series with an article explaining how to customize menu item icons.</ctrl></p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/customizing-workspace-context-menu/' rel='bookmark' title='Customizing Workspace context-menu'>Customizing Workspace context-menu</a> <small>Matlab's Workspace table context-menu can be configured with user-defined actions - this article explains how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/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></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/customizing-menu-items-part-2/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Customizing menu items part 1</title><link>http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/</link> <comments>http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/#comments</comments> <pubDate>Wed, 25 Apr 2012 18:14:08 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <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[Matlab menus can be customized in a variety of undocumented manners - first article of a series.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes-2/' rel='bookmark' title='Customizing uitree nodes &#8211; part 2'>Customizing uitree nodes &#8211; part 2</a> <small>This article shows how Matlab GUI tree nodes can be customized with checkboxes and similar controls...</small></li></ol><pre> </pre>]]></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="http://undocumentedmatlab.com/blog/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="http://undocumentedmatlab.com/blog/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="http://undocumentedmatlab.com/blog/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>.</p><p>Menu callbacks generally use internal <a
target="_blank" href="http://undocumentedmatlab.com/blog/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.</p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">filemenufcn FileClose;
editmenufcn<span style="color: #080;">&#40;</span>hFig,<span style="color:#A020F0;">'EditPaste'</span><span style="color: #080;">&#41;</span>;</pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">uimenufcn<span style="color: #080;">&#40;</span><span style="color: #33f;">0</span>, <span style="color:#A020F0;">'WindowCommandWindow'</span><span style="color: #080;">&#41;</span>;</pre></div></div><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.</p><p><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;-&#8217; 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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">labels = str2mat<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'&amp;File'</span>, <span style="color: #F0F;">...</span>    <span style="color: #228B22;">% File top menu</span>
           <span style="color:#A020F0;">'&gt;&amp;New^n'</span>, <span style="color: #F0F;">...</span>           <span style="color: #228B22;">% File=&gt;New</span>
           <span style="color:#A020F0;">'&gt;&amp;Open'</span>, <span style="color: #F0F;">...</span>            <span style="color: #228B22;">% File=&gt;Open</span>
           <span style="color:#A020F0;">'&gt;&gt;Open &amp;document^d'</span>, <span style="color: #F0F;">...</span>    <span style="color: #228B22;">% File=&gt;Open=&gt;doc</span>
           <span style="color:#A020F0;">'&gt;&gt;Open &amp;graph^g'</span>, <span style="color: #F0F;">...</span>       <span style="color: #228B22;">% File=&gt;Open=&gt;graph</span>
           <span style="color:#A020F0;">'&gt;-------'</span>, <span style="color: #F0F;">...</span>          <span style="color: #228B22;">% File=&gt;separator line</span>
           <span style="color:#A020F0;">'&gt;&amp;Save^s'</span>, <span style="color: #F0F;">...</span>          <span style="color: #228B22;">% File=&gt;Save</span>
           <span style="color:#A020F0;">'&amp;Edit'</span>, <span style="color: #F0F;">...</span>		<span style="color: #228B22;">% Edit top menu</span>
           <span style="color:#A020F0;">'&amp;View'</span>, <span style="color: #F0F;">...</span>		<span style="color: #228B22;">% View top menu</span>
           <span style="color:#A020F0;">'&gt;&amp;Axis^a'</span>, <span style="color: #F0F;">...</span>          <span style="color: #228B22;">% View=&gt;Axis</span>
           <span style="color:#A020F0;">'&gt;&amp;Selection region^r'</span><span style="color: #080;">&#41;</span>; <span style="color: #228B22;">% View=&gt;Selection</span>
calls = str2mat<span style="color: #080;">&#40;</span><span style="color:#A020F0;">''</span>, <span style="color: #F0F;">...</span>		<span style="color: #228B22;">% no action: File top menu</span>
           <span style="color:#A020F0;">'disp('</span><span style="color:#A020F0;">'New'</span><span style="color:#A020F0;">')'</span>, <span style="color: #F0F;">...</span>
           <span style="color:#A020F0;">''</span>, <span style="color: #F0F;">...</span>			<span style="color: #228B22;">% no action: Open sub-menu</span>
           <span style="color:#A020F0;">'disp('</span><span style="color:#A020F0;">'Open doc'</span><span style="color:#A020F0;">')'</span>, <span style="color: #F0F;">...</span>
           <span style="color:#A020F0;">'disp('</span><span style="color:#A020F0;">'Open graph'</span><span style="color:#A020F0;">')'</span>, <span style="color: #F0F;">...</span>
           <span style="color:#A020F0;">''</span>, <span style="color: #F0F;">...</span>			<span style="color: #228B22;">% no action: Separator</span>
           <span style="color:#A020F0;">'disp('</span><span style="color:#A020F0;">'Save'</span><span style="color:#A020F0;">')'</span>, <span style="color: #F0F;">...</span>
           <span style="color:#A020F0;">''</span>, <span style="color: #F0F;">...</span>			<span style="color: #228B22;">% no action: Edit top menu</span>
           <span style="color:#A020F0;">''</span>, <span style="color: #F0F;">...</span>			<span style="color: #228B22;">% no action: View top menu</span>
           <span style="color:#A020F0;">'disp('</span><span style="color:#A020F0;">'View axis'</span><span style="color:#A020F0;">')'</span>, <span style="color: #F0F;">...</span>
           <span style="color:#A020F0;">'disp('</span><span style="color:#A020F0;">'View selection region'</span><span style="color:#A020F0;">')'</span><span style="color: #080;">&#41;</span>;
handles = makemenu<span style="color: #080;">&#40;</span>hFig, labels, calls<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hFig,<span style="color:#A020F0;">'menuBar'</span>,<span style="color:#A020F0;">'none'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 277px"><img
alt="A simple figure menu" src="http://UndocumentedMatlab.com/images/makemenu.png" title="A simple figure menu" width="267" height="148"/><p
class="wp-caption-text">A simple figure menu</p></div></center></p><h3 id="HTML">Customizing menus via HTML</h3><p>Since menu items share the same <a
target="_blank" href="http://undocumentedmatlab.com/blog/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.</p><p>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).</p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">txt1 = <span style="color:#A020F0;">'&lt;html&gt;&lt;b&gt;&lt;u&gt;&lt;i&gt;Save&lt;/i&gt;&lt;/u&gt;'</span>;
txt2 = <span style="color:#A020F0;">'&lt;font color=&quot;red&quot;&gt;&lt;sup&gt;this file&lt;/sup&gt;&lt;/font&gt;&lt;/b&gt;&lt;/html&gt;'</span>;
txt3 = <span style="color:#A020F0;">'&lt;br /&gt;this file as...'</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>findall<span style="color: #080;">&#40;</span>hFig,<span style="color:#A020F0;">'tag'</span>,<span style="color:#A020F0;">'figMenuFileSave'</span><span style="color: #080;">&#41;</span>,   <span style="color:#A020F0;">'Label'</span>,<span style="color: #080;">&#91;</span>txt1,txt2<span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>findall<span style="color: #080;">&#40;</span>hFig,<span style="color:#A020F0;">'tag'</span>,<span style="color:#A020F0;">'figMenuFileSaveAs'</span><span style="color: #080;">&#41;</span>, <span style="color:#A020F0;">'Label'</span>,<span style="color: #080;">&#91;</span>txt1,txt3<span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 195px"><img
alt="A multi-line HTML-rendered menu item" src="http://UndocumentedMatlab.com/images/uimenu2.png" title="A multi-line HTML-rendered menu item" width="185" height="184"/><p
class="wp-caption-text">A multi-line HTML-rendered menu item</p></div></center></p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hMenuItem, <span style="color:#A020F0;">'Label'</span>,<span style="color: #080;">&#91;</span><span style="color:#A020F0;">'&lt;html&gt;&amp;2: C:\My Documents\doc.txt&lt;br /&gt;'</span>
   <span style="color:#A020F0;">'&lt;font size=&quot;-1&quot; face=&quot;Courier New&quot; color=&quot;red&quot;&gt;&amp;nbsp;&amp;nbsp; '</span>
   <span style="color:#A020F0;">'Date: 15-Jun-2011 13:23:45&lt;br /&gt;&amp;nbsp;&amp;nbsp; Size: 123 KB&lt;/font&gt;&lt;/html&gt;'</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 421px"><img
alt="HTML-rendered menu items" src="http://UndocumentedMatlab.com/images/uimenu2b.png" title="HTML-rendered menu items" width="411" height="246"/><p
class="wp-caption-text">HTML-rendered menu items</p></div></center></p><p>Much more complex customizations can be achieved using Java. So stay tuned to part 2 of this mini-series&#8230;</p><p>Note: Menu customization is explored in depth in section 4.6 of my <a
target="_blank" href="http://undocumentedmatlab.com/matlab-java-book/">book</a>.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/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><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes-2/' rel='bookmark' title='Customizing uitree nodes &#8211; part 2'>Customizing uitree nodes &#8211; part 2</a> <small>This article shows how Matlab GUI tree nodes can be customized with checkboxes and similar controls...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/feed/</wfw:commentRss> <slash:comments>5</slash:comments> </item> <item><title>Matlab-Java memory leaks, performance</title><link>http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/</link> <comments>http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/#comments</comments> <pubDate>Fri, 20 Jan 2012 00:56:10 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Memory]]></category> <category><![CDATA[Semi-documented feature]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[Performance]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2665</guid> <description><![CDATA[Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/profiling-matlab-memory-usage/' rel='bookmark' title='Profiling Matlab memory usage'>Profiling Matlab memory usage</a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/preallocation-performance/' rel='bookmark' title='Preallocation performance'>Preallocation performance</a> <small>Preallocation is a standard Matlab speedup technique. Still, it has several undocumented aspects. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/performance-scatter-vs-line/' rel='bookmark' title='Performance: scatter vs. line'>Performance: scatter vs. line</a> <small>In many circumstances, the line function can generate visually-identical plots as the scatter function, much faster...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>There are several ways of retrieving information from a Java object into Matlab. On the face of it, all these methods look similar. But it turns out that there are important differences between them in terms of memory leakage and performance.</p><h3 id="Problem">The problem: &#8220;Matlab crashes&#8221; &#8211; now go figure&#8230;</h3><p>A client of one of my Matlab programs recently complained that Matlab crashes after several hours of extensive use of the program. The problem looked like something that is memory related (messages such as Matlab&#8217;s out-of-memory error or Java&#8217;s heap-space error). Apparently this happens even on 64-bit systems having lots of memory, where memory should never be a problem.</p><p>Well, we know that this is only in theory, but in practice Matlab&#8217;s internal memory management has problems that occasionally lead to such crashes. This is one of the reasons, by the way, that recent Matlab releases have added the preference option of increasing the default Java heap space (the previous way to do this was <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/support/solutions/en/data/1-18I2C/">a bit complex</a>). Still, even with a high Java heap space setting and lots of RAM, Matlab crashed after using my program for several hours.</p><p>Not pleasant at all, even a bit of an embarrassment for me. I&#8217;m used to crashing Matlab, but only as a result of my playing around with the internals &#8211; I would hate it to happen to my clients.</p><h3 id="Finding">Finding the leak</h3><p>While we can do little with Matlab&#8217;s internal memory manager, I started searching for the exact location of the memory leak and then to find a way to overcome it. I&#8217;ll save readers the description about the grueling task of finding out exactly where the memory leak occurred in a program that has thousands of lines of code and where events get fired asynchronously on a constant basis. <a
target="_blank" href="http://undocumentedmatlab.com/blog/undocumented-profiler-options/">Matlab Profiler&#8217;s undocumented memory profiling option</a> helped me quite a bit, as well as lots of intuition and trial-and-error. Detecting memory leak is never easy, and I consider myself somewhat lucky this time to have both detected the leak source and a workaround.</p><p>It turned out that the leakage happens in a callback that gets invoked multiple times per second by a Java object (see related articles <a
target="_blank" href="http://undocumentedmatlab.com/blog/uicontrol-callbacks/">here</a> and <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/">here</a>). Each time the Matlab callback function is invoked, it reads the event information from the supplied Java event-data (the callback&#8217;s second input parameter). Apparently, about 1KB of memory gets leaked whenever this event-data is being read. This may appear a very small leak, but multiply this by some 50-100K callback invocations per hour and you get a leakage of 50-100MB/hour. Not a small leak at all; more of a flood you could say&#8230;</p><h3 id="get">Using <i><b>get</b>()</i></h3><p>The leakage culprit turned out to be the following code snippet:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% 160 uSecs per call, with memory leak</span>
eventData  = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>hEventData,<span style="color: #080;">&#123;</span><span style="color:#A020F0;">'EventName'</span>,<span style="color:#A020F0;">'ParamNames'</span>,<span style="color:#A020F0;">'EventData'</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
eventName  = eventData<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span>;
paramNames = eventData<span style="color: #080;">&#123;</span><span style="color: #33f;">2</span><span style="color: #080;">&#125;</span>;
paramData  = eventData<span style="color: #080;">&#123;</span><span style="color: #33f;">3</span><span style="color: #080;">&#125;</span>.<span style="color: #0000FF;">cell</span>;</pre></div></div><p>In this innocent-looking code, <code>hEventData</code> is a Java object that contains the <b>EventName, ParamNames, EventData</b> properties: <b>EventName</b> is a Java <code>String</code>, that is automatically converted by Matlab&#8217;s <i><b>get</b>()</i> function into a Matlab string (<i><b>char</b></i> array); <b>ParamNames</b> is a Java array of <code>String</code>s, that gets automatically converted into a Matlab cell-array of string; and <b>EventData</b> is a Java array of <code>Object</code>s that needs to be converted into a Matlab cell array using the built-in <i><b>cell</b></i> function, as <a
target="_blank" href="http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/">described</a> in one of my recent articles.</p><p>The code is indeed innocent, works really well and is actually extremely fast: each invocation takes of this code segment takes less than 0.2 millisecs. Unfortunately, because of the memory leak I needed to find a better alternative.</p><h3 id="handle">Using <i><b>handle</b>()</i></h3><p>The first idea was to use the built-in <i><b>handle</b>()</i> function, under the assumption that it would solve the memory leak, as <a
target="_blank" rel="nofollow" href="http://mathforum.org/kb/message.jspa?messageID=5950839">reported here</a>. In fact, MathWorks specifically advises to use <i><b>handle</b>()</i> rather than to work with &#8220;naked&#8221; Java objects, when <a
target="_blank" href="http://undocumentedmatlab.com/blog/uicontrol-callbacks/#memory_leak">setting Java object callbacks</a>. The official documentation of the <i><b>set</b></i> function <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/ref/set.html#f67-433534">says</a>:</p><blockquote><p>Do not use the set function on Java objects as it will cause a memory leak.</p></blockquote><p>It stands to reason then that a similar memory leak happens with <i><b>get</b></i> and that a similar use of <i><b>handle</b></i> would solve this problem:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% 300 uSecs per call, with memory leak</span>
s = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span>hEventData<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
eventName  = s.<span style="">EventName</span>;
paramNames = s.<span style="">ParamNames</span>;
paramData  = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>s.<span style="">EventData</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Unfortunately, this variant, although working correctly, still leaks memory, and also performs almost twice as worse than the original version, taking some 0.3 milliseconds to execute per invocation. Looks like this is a dead end.</p><h3 id="accessor">Using Java accessor methods</h3><p>The next attempt was to use the Java object&#8217;s internal accessor methods for the requested properties. These are <code>public</code> methods of the form <i>getXXX(), isXXX(), setXXX()</i> that enable Matlab to treat XXX as a property by its <i><b>get</b></i> and <i><b>set</b></i> functions. In our case, we need to use the getter methods, as follows:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% 380 uSecs per call, no memory leak</span>
eventName  = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>hEventData.<span style="">getEventName</span><span style="color: #080;">&#41;</span>;
paramNames = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>hEventData.<span style="">getParamNames</span><span style="color: #080;">&#41;</span>;
paramData  = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>hEventData.<span style="">getEventData</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Here, the method <i>getEventName()</i> returns a Java <code>String</code>, that we convert into a Matlab string using the <i><b>char</b></i> function. In our previous two variants, the <i><b>get</b></i> function did this conversion for us automatically, but when we use the Java method directly we need to convert the results ourselves. Similarly, when we call <i>getParamNames()</i>, we need to use the <i><b>cell</b></i> function to convert the Java <code>String[]</code> array into a Matlab cell array.</p><p>This version at last doesn&#8217;t leak any memory. Unfortunately, it has an even worse performance: each invocation takes almost 0.4 milliseconds. The difference may seem insignificant. However, recall that this callback gets called dozens of times each second, so the total adds up quickly. It would be nice if there were a faster alternative that does not leak any memory.</p><h3 id="struct">Using <i><b>struct</b>()</i></h3><p>Luckily, I found just such an alternative. At 0.24 millisecs per invocation, it is almost as fast as the leaky best-performance original <i><b>get</b></i> version. Best of all, it leaks no memory, at least none that I could detect.</p><p>The mechanism relies on the little-known fact that public fields of Java objects can be retrieved in Matlab using the built-in <i><b>struct</b></i> function. For example:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; fields = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>java.<span style="">awt</span>.<span style="color: #0000FF;">Rectangle</span><span style="color: #080;">&#41;</span>
fields = 
             x<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
             y<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
         width<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
        height<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
      OUT_LEFT<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>
       OUT_TOP<span style="color: #F0F;">:</span> <span style="color: #33f;">2</span>
     OUT_RIGHT<span style="color: #F0F;">:</span> <span style="color: #33f;">4</span>
    OUT_BOTTOM<span style="color: #F0F;">:</span> <span style="color: #33f;">8</span>
&nbsp;
&gt;&gt; fields = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>java.<span style="">awt</span>.<span style="">Dimension</span><span style="color: #080;">&#41;</span>
fields = 
     width<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
    height<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span></pre></div></div><p>Note that this useful mechanism is not mentioned in <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_external/f4873.html#f46643">the main documentation page for accessing Java object fields</a>, although it is indeed mentioned in <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_external/f6671.html#f61403">another doc-page</a> &#8211; I guess this is a documentation oversight.</p><p>In any case, I converted my Java object to use public (rather than private) fields, so that I could use this <i><b>struct</b></i> mechanism (Matlab can only access public fields). Yes I know that using private fields is a better programming practice and all that (I&#8217;ve programmed OOP for some 15 years&#8230;), but sometimes we need to do ugly things in the interest of performance. The latest version now looks like this:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% 240 uSecs per call, no memory leak</span>
s = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>hEventData<span style="color: #080;">&#41;</span>;
eventName  = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>s.<span style="">eventName</span><span style="color: #080;">&#41;</span>;
paramNames = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>s.<span style="">paramNames</span><span style="color: #080;">&#41;</span>;
paramData  = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>s.<span style="">eventData</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>This solved the memory leakage issue for my client. I felt fortunate that I was not only able to detect Matlab&#8217;s memory leak but also find a working workaround without sacrificing performance or functionality.</p><p>In this particular case, I was lucky to have full control over my Java object, to be able to convert its fields to become public. Unfortunately, we do not always have similar control over the object that we use, because they were coded by a third party.</p><p>By the way, Matlab itself uses this <i><b>struct</b></i> mechanism in its code-base. For example, Matlab timers are implemented using Java objects (<code>com.mathworks.timer.TimerTask</code>). The timer callback in Matlab code converts the Java timer event data into a Matlab struct using the <i><b>struct</b></i> function, in <i>%matlabroot%/toolbox/matlab/iofun/@timer/timercb.m</i>. The users of the timer callbacks then get passed a simple Matlab EventData struct without ever knowing that the original data came from a Java object.</p><p>As an interesting corollary, this same <i><b>struct</b></i> mechanism can be used to detect internal properties of Matlab class objects. For example, in the timers again, we can get the underlying timer&#8217;s Java object as follows (note the highlighted warning, which I find a bit ironic given the context):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; timerObj = timerfind
&nbsp;
   Timer Object<span style="color: #F0F;">:</span> timer-<span style="color: #33f;">1</span>
&nbsp;
   Timer Settings
      ExecutionMode<span style="color: #F0F;">:</span> singleShot
             Period<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>
           BusyMode<span style="color: #F0F;">:</span> drop
            Running<span style="color: #F0F;">:</span> off
&nbsp;
   Callbacks
           TimerFcn<span style="color: #F0F;">:</span> @myTimerFcn
           ErrorFcn<span style="color: #F0F;">:</span> <span style="color:#A020F0;">''</span>
           StartFcn<span style="color: #F0F;">:</span> <span style="color:#A020F0;">''</span>
            StopFcn<span style="color: #F0F;">:</span> <span style="color:#A020F0;">''</span>
&nbsp;
&gt;&gt; timerFields = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>timerObj<span style="color: #080;">&#41;</span>
<span style="display:block;background-color: #ffc;"><span style="color: #0000FF;">Warning</span><span style="color: #F0F;">:</span> Calling <span style="color: #0000FF;">STRUCT</span> on an object prevents the object from hiding its implementation details and should thus be avoided.</span><span style="display:block;background-color: #ffc;"><span style="">Use</span> <span style="color: #0000FF;">DISP</span> or DISPLAY to see the visible public details of an object. <span style="">See</span> <span style="color:#A020F0;">'help struct'</span> <span style="color: #0000FF;">for</span> <span style="color: #0000FF;">more</span> information.</span><span style="display:block;background-color: #ffc;"><span style="color: #080;">&#40;</span><span style="color: #0000FF;">Type</span> &quot;warning off MATLAB<span style="color: #F0F;">:</span>structOnObject&quot; to suppress this <span style="color: #0000FF;">warning</span>.<span style="color: #080;">&#41;</span></span>timerFields = 
         ud<span style="color: #F0F;">:</span> <span style="color: #080;">&#123;</span><span style="color: #080;">&#125;</span>
    jobject<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 javahandle.<span style="">com</span>.<span style="">mathworks</span>.<span style="">timer</span>.<span style="">TimerTask</span><span style="color: #080;">&#93;</span></pre></div></div><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/profiling-matlab-memory-usage/' rel='bookmark' title='Profiling Matlab memory usage'>Profiling Matlab memory usage</a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/preallocation-performance/' rel='bookmark' title='Preallocation performance'>Preallocation performance</a> <small>Preallocation is a standard Matlab speedup technique. Still, it has several undocumented aspects. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/performance-scatter-vs-line/' rel='bookmark' title='Performance: scatter vs. line'>Performance: scatter vs. line</a> <small>In many circumstances, the line function can generate visually-identical plots as the scatter function, much faster...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/feed/</wfw:commentRss> <slash:comments>20</slash:comments> </item> <item><title>Common javacomponent problems</title><link>http://undocumentedmatlab.com/blog/common-javacomponent-problems/</link> <comments>http://undocumentedmatlab.com/blog/common-javacomponent-problems/#comments</comments> <pubDate>Wed, 07 Dec 2011 18:00:38 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[GUI]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[Semi-documented function]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[GUIDE]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2607</guid> <description><![CDATA[The javacomponent function is very useful for placing Java components on-screen, but has a few quirks.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/javacomponent/' rel='bookmark' title='The javacomponent function'>The javacomponent function</a> <small>Matlab's built-in javacomponent function can be used to display Java components in Matlab application - this article details its usages and limitations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/javacomponent-background-color/' rel='bookmark' title='Javacomponent background color'>Javacomponent background color</a> <small>This article explains how to align Java component background color with a Matlab color....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-and-the-event-dispatch-thread-edt/' rel='bookmark' title='Matlab and the Event Dispatch Thread (EDT)'>Matlab and the Event Dispatch Thread (EDT)</a> <small>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes-2/' rel='bookmark' title='Customizing uitree nodes &#8211; part 2'>Customizing uitree nodes &#8211; part 2</a> <small>This article shows how Matlab GUI tree nodes can be customized with checkboxes and similar controls...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>The <i><b>javacomponent</b></i> function, which I described <a
target="_blank" href="http://UndocumentedMatlab.com/blog/javacomponent/">here</a> last year, is a very important built-in Matlab function that enables placing Java components in Matlab figure GUI. Using <i><b>javacomponent</b></i> is pretty straight-forward. However, there are a few quirks that users should be aware of. In today&#8217;s article I&#8217;ll try to highlight some of them and discuss workarounds.</p><h3 id="figure-vis">Figure visibility</h3><p>Java components can only be placed onscreen when their containing Matlab figure has been made visible. This means that calls to <i><b>javacomponent</b></i> cannot be placed at the GUIDE-created *_OpeningFcn() function, because that function is invoked <i>before</i> the figure window is made visible.</p><p>Of course, we can always force the figure to become visible by setting the figure&#8217;s <b>Visible</b> property to <code>'on'</code> in this function, before calling our <i><b>javacomponent</b></i>s. But IMHO, a better option would be to simply place the <i><b>javacomponent</b></i>s in the corresponding GUIDE-created *_OutputFcn() function, which is invoked <i>after</i> the figure window is made visible.</p><h3 id="parent-vis">Auto-hiding with parent container</h3><p>Java components are not automatically hidden with their ancestor container panel. This is also the root cause of the failure of Java components to disappear when switching tabs in a <i><b>uitab</b></i>.</p><p>One simple workaround for this that I often use is to link the <b>Visible</b> properties of the <i><b>javacomponent</b></i> container and the parent container:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jButton = javax.<span style="">swing</span>.<span style="">JButton</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'click me!'</span><span style="color: #080;">&#41;</span>;
<span style="color: #080;">&#91;</span>jhButton, hContainer<span style="color: #080;">&#93;</span> = javacomponent<span style="color: #080;">&#40;</span>jButton, <span style="color: #080;">&#91;</span><span style="color: #33f;">100</span>,<span style="color: #33f;">100</span>,<span style="color: #33f;">60</span>,<span style="color: #33f;">30</span><span style="color: #080;">&#93;</span>, hParent<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">setappdata</span><span style="color: #080;">&#40;</span>hParent, <span style="color:#A020F0;">'linked_props__'</span>, linkprop<span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span>hParent,hContainer<span style="color: #080;">&#93;</span>,<span style="color:#A020F0;">'Visible'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>This has indeed been fixed in R2010b. If you ask me, this should have been standard behavior of <i><b>javacomponent</b></i> since the very beginning&#8230;</p><p>Although there is no need for the workaround in R2010b onward, I usually keep the workaround because it doesn&#8217;t hurt and enables backward compatibility for users who may have an older Matlab release.</p><h3 id="parent-types">Possible parent container types</h3><p><i><b>javacomponent</b></i> accepts parent handles that are figures, toolbars, <i><b>uipanel</b></i>s, or <a
target="_blank" href="http://UndocumentedMatlab.com/blog/matlab-layout-managers-uicontainer-and-relatives"><i><b>uicontainer</b></i>s</a> (some of these are not documented as possible parents in some Matlab releases, but they are). Since R2008a, parents of type <a
target="_blank" href="http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool/"><i><b>uisplittool</b></i> and <i><b>uitogglesplittool</b></i></a> can also be used. Unfortunately, frames are not <i><b>uicontainer</b></i>s and, therefore, cannot be used as <i><b>javacomponent</b></i> parents.</p><p>Note: Due to a bug in R2007a, <i><b>javacomponent</b></i>s cannot be added to <i><b>uicontainer</b></i>s, since <i>javacomponent.m</i> checks if <code>isa(hParent,'uicontainer')</code> (and similarly for <code>'uiflowcontainer', 'uigridcontainer'</code>), instead of <code>isa(hParent,'hg.uicontainer')</code> (and similarly for the others). If we modify <i>javacomponent.m</i> accordingly (add &#8220;hg.&#8221; in lines 98-100), this bug will be fixed. Since R2007b, <code>isa(…,'hg.uicontainer')</code> is equivalent to <code>isa(…,'uicontainer')</code>, so this fix is unnecessary.</p><h3 id="inputs">Input parameters</h3><p>Unlike many other Matlab functions, <i><b>javacomponent</b></i> does not accept optional parameter-value (P-V) pairs. If we want to customize the appearance of the Java component, it is better to create it , customize it, and only then to present it onscreen using <i><b>javacomponent</b></i>. If we first present the component and then customize it, there might be all sorts of undesirable flicker effects while the component is changing its properties.</p><p>One of the parameters that unfortunately cannot be customized before calling <i><b>javacomponent</b></i> is the component&#8217;s position onscreen. <i><b>javacomponent</b></i> only accepts a position vector in pixel units. To modify the component to use normalized units, we need to modify the container&#8217;s properties:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jButton = javax.<span style="">swing</span>.<span style="">JButton</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'click me!'</span><span style="color: #080;">&#41;</span>;
<span style="color: #080;">&#91;</span>jhButton, hContainer<span style="color: #080;">&#93;</span> = javacomponent<span style="color: #080;">&#40;</span>jButton, <span style="color: #080;">&#91;</span><span style="color: #33f;">100</span>,<span style="color: #33f;">100</span>,<span style="color: #33f;">60</span>,<span style="color: #33f;">30</span><span style="color: #080;">&#93;</span>, <span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hContainer, <span style="color:#A020F0;">'Units'</span>,<span style="color:#A020F0;">'norm'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Similarly, we can set the container&#8217;s <b>UserData</b> and <b>ApplicationData</b> only after the call to <i><b>javacomponent</b></i>.</p><h3 id="bg-color">Background color</h3><p>The default background color of <i><b>javacomponent</b></i>s is a slightly different shade of gray than the default <i><b>uicontrol</b></i> background color. Please refer to my recent <a
target="_blank" href="http://UndocumentedMatlab.com/blog/javacomponent-background-color/">article</a> for a detailed discussion of this issue.</p><h3 id="alignment">Vertical alignment</h3><p>Java components are slightly mis-aligned vertically with combo-box (<b>Style</b>=&#8217;popup&#8217;) <i><b>uicontrol</b></i>s, even when positioned using the same Y position. This is actually due to an apparent bug in Matlab&#8217;s implementation of the combo-box <i><b>uicontrol</b></i>, and not in the Java component&#8217;s: Apparently, the Matlab control does not obey its specified height and uses some other default height.</p><p>If we place <i><b>javacomponent</b></i>s side-by-side with a regular Matlab popup <i><b>uicontrol</b></i>s and give them all the same Y position, we can see this mis-alignment. It is only a few pixels, but the effect is visible and disturbing. To fix it, we need to add a small offset to the <i><b>javacomponent</b></i>&#8216;s container&#8217;s <b>Position</b> property to make both the initial Y position slightly lower, and the height value slightly higher than the values for the corresponding Matlab combo-box control.</p><h3 id="callbacks">Callbacks</h3><p>Unlike Matlab <i><b>uicontrol</b></i> callbacks, Java callbacks are activated even when the affected value does not change. Therefore, setting a value in the component&#8217;s callback could well cause an infinite loop of invoked callbacks.</p><p>Matlab programmers often use the practice of modifying component value within the callback function, as a means of fixing user-entered values to be within a certain data range, or in order to format the displayed value. This is relatively harmless in Matlab (if done correctly) since updating a Matlab <i><b>uicontrol</b></i>&#8216;s value to the current value does not retrigger the callback. But since this is not the case with Java callbacks, users should beware not to use the same practice there. In cases where this cannot be avoided, users should at least implement some sort of <a
target="_blank" href="http://undocumentedmatlab.com/blog/controlling-callback-re-entrancy/">callback re-entrancy prevention logic</a>.</p><h3 id="EDT">EDT</h3><p>Java components typically need to use the independent Java Event processing Thread (EDT). EDT is very important for Matlab GUI, as explained in <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-and-the-event-dispatch-thread-edt/">this article</a>. Failure to use EDT properly in Matlab can lead to unexpected GUI behavior and even Matlab hangs or crashes.</p><p>If the <i><b>javacomponent</b></i> function is called in a very specific syntax format where the first input arg is a string (the name of the Java class to be created), then the newly-created component is placed on the EDT. However, this is not the normal manner in which <i><b>javacomponent</b></i> is used: A much more typical use-case is where <i><b>javacomponent</b></i> is passed a reference handle to a previously-created Java component. In such cases, it is the user&#8217;s responsibility to place the component on the EDT. Until R2008a this should be done using the <i><b>awtcreate</b></i> function; since R2008b, we can use the much simpler <i><b>javaObjectEDT</b></i> function (<i><b>javaObjectEDT</b></i> actually existed since R2008a, but was buggy on that release so I suggest using it only starting in R2008b; it became documented starting in R2009a). In fact, modern <i><b>javacomponent</b></i> saves us the trouble, by automatically using <i><b>javaObjectEDT</b></i> to auto-delegate the component onto the EDT, even if we happen to have created it on the MT.</p><p>The paragraph above may lead us to believe that we only need to worry about EDT in R2008a and earlier. Unfortunately, this is not the case. Modern GUI requires using many sub-components, that are attached to their main component (e.g., CellRenderers and CellEditors). <i><b>javacomponent</b></i> only bothers to place the main component on the EDT &#8211; not any of the sub-components. We need to handle these separately. Liberally auto-delegating components to the EDT seems like a safe and painless habit to have.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/javacomponent/' rel='bookmark' title='The javacomponent function'>The javacomponent function</a> <small>Matlab's built-in javacomponent function can be used to display Java components in Matlab application - this article details its usages and limitations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/javacomponent-background-color/' rel='bookmark' title='Javacomponent background color'>Javacomponent background color</a> <small>This article explains how to align Java component background color with a Matlab color....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-and-the-event-dispatch-thread-edt/' rel='bookmark' title='Matlab and the Event Dispatch Thread (EDT)'>Matlab and the Event Dispatch Thread (EDT)</a> <small>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes-2/' rel='bookmark' title='Customizing uitree nodes &#8211; part 2'>Customizing uitree nodes &#8211; part 2</a> <small>This article shows how Matlab GUI tree nodes can be customized with checkboxes and similar controls...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/common-javacomponent-problems/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Controlling callback re-entrancy</title><link>http://undocumentedmatlab.com/blog/controlling-callback-re-entrancy/</link> <comments>http://undocumentedmatlab.com/blog/controlling-callback-re-entrancy/#comments</comments> <pubDate>Wed, 10 Aug 2011 18:00:57 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Guest bloggers]]></category> <category><![CDATA[GUI]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[COM]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Malcolm Lidierth]]></category> <category><![CDATA[Pure Matlab]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2403</guid> <description><![CDATA[Callback reentrancy is a major problem for frequently-fired events. Luckily, it can easily be solved.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/continuous-slider-callback/' rel='bookmark' title='Continuous slider callback'>Continuous slider callback</a> <small>Matlab slider uicontrols do not enable a continuous-motion callback by default. This article explains how this can be achieved using undocumented features....</small></li><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/uicontrol-callbacks/' rel='bookmark' title='Uicontrol callbacks'>Uicontrol callbacks</a> <small>This post details undocumented callbacks exposed by the underlying Java object of Matlab uicontrols, that can be used to modify the control's behavior in a multitude of different events...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><i>I&#8217;d like to welcome guest blogger <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/23816">Malcolm Lidierth</a> of King&#8217;s College London. Malcolm is well known in the Matlab-Java community for his <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/15580-using-java-swing-components-in-matlab">jcontrol utility</a>. Some months ago, I mentioned his work on another File Exchange contribution, <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/28326-mutilities">MUtilities</a> when I discussed <a
target="_blank" href="http://undocumentedmatlab.com/blog/transparent-matlab-figure-window/">transparent Matlab figure windows</a>. Today, Malcolm discusses one of his lesser-known but extremely important <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26027-ismultiplecall">isMultipleCall utility</a>.</i></p><p>Every now and again, a very simple bit of code turns out to be more useful than the author initially imagined. Something I have repeatedly used is the <i><b>isMultipleCall</b></i> function which I <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26027-ismultiplecall">posted</a> to MATLAB Central&#8217;s File Exchange a year or so ago.</p><p>The <i><b>isMultipleCall</b></i> function uses fully-documented pure-MATLAB to extend the control that can be achieved over callbacks.</p><p>Here was the problem: I had a modular system built in MATLAB which allowed third-party developers to add their own plugins. I wanted a mechanism to force the dismissal (&#8220;bail-out&#8221;) of a callback even when the <b>Interruptible</b> property of the parent object was set to &#8216;on&#8217;. Such callback re-entrancy issues are common for rapidly-firing events, and debugging and fixing them is usually <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/answers/5809-how-to-implement-a-speed-limit-for-gui-button-press">not easy</a>.</p><p>The callback&#8217;s dismissal code would need to be fast because it might be called many dozens of times, e.g. in a <b>WindowButtonMotion</b> callback. An obvious approach was to check the function call stack using MATLAB&#8217;s <i><b>dbstack</b></i> function. Although, at first, this seemed likely to be too slow, profiling showed it was not – taking &lt; 40&micro;sec per call &#8211; and within a <b>WindowButtonMotion</b> callback in a real GUI, I could not perceive any slowing of the code.</p><p>Here is the function:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> <span style="color: #0000FF;">flag</span>=isMultipleCall<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
  <span style="color: #0000FF;">flag</span> = <span style="color: #0000FF;">false</span>; 
  <span style="color: #228B22;">% Get the stack</span>
  s = <span style="color: #0000FF;">dbstack</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
  <span style="color: #0000FF;">if</span> numel<span style="color: #080;">&#40;</span>s<span style="color: #080;">&#41;</span>&lt; =<span style="color: #33f;">2</span>
    <span style="color: #228B22;">% Stack too short for a multiple call</span>
    <span style="color: #0000FF;">return</span>
  <span style="color: #0000FF;">end</span>
&nbsp;
  <span style="color: #228B22;">% How many calls to the calling function are in the stack?</span>
  names = <span style="color: #080;">&#123;</span>s<span style="color: #080;">&#40;</span><span style="color: #F0F;">:</span><span style="color: #080;">&#41;</span>.<span style="">name</span><span style="color: #080;">&#125;</span>;
  TF = <span style="color: #0000FF;">strcmp</span><span style="color: #080;">&#40;</span>s<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>.<span style="">name</span>,names<span style="color: #080;">&#41;</span>;
  count = <span style="color: #0000FF;">sum</span><span style="color: #080;">&#40;</span>TF<span style="color: #080;">&#41;</span>;
  <span style="color: #0000FF;">if</span> count&gt;<span style="color: #33f;">1</span>
    <span style="color: #228B22;">% More than 1</span>
    <span style="color: #0000FF;">flag</span> = <span style="color: #0000FF;">true</span>; 
  <span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">end</span></pre></div></div><p>With <i><b>isMultipleCall</b></i> invoked from another function (see note below), <i><b>dbstack</b></i> will return a structure with a minimum of 2 elements – the first relating to <i><b>isMultipleCall</b></i> itself and the second to the calling function. So with <i><b>numel</b></i>(s) &lt;= 2, there can be no multiple calls and we can return false immediately thus saving time in doing any further testing.  For <i><b>numel</b></i>(s) &gt; 2 we simply check to see whether the calling functions referenced in s(2) appears anywhere else on the stack. If it does, then we return true; otherwise false.</p><p>Then, in our callback code we simply use:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">if</span> isMultipleCall<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;  <span style="color: #0000FF;">return</span>;  <span style="color: #0000FF;">end</span></pre></div></div><p>If this line is placed first in the callback function code, it essentially mimics the behavior that you might expect after setting the <b>Interruptible</b> property of the event firing object to &#8216;off&#8217;. Adding a <i><b>drawnow()</b></i> at the end of the callback will ensure that any waiting callbacks in the queue are dismissed:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> MyCallback<span style="color: #080;">&#40;</span>hObj, EventData<span style="color: #080;">&#41;</span>
  <span style="color: #228B22;">% Quick bail-out if callback code is called before another has ended</span>
  <span style="color: #0000FF;">if</span> isMultipleCall<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;  <span style="color: #0000FF;">return</span>;  <span style="color: #0000FF;">end</span>
&nbsp;
  <span style="color: #F0F;">...</span>  <span style="color: #228B22;">% do some actual callback work here</span>
  <span style="color: #0000FF;">drawnow</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>There are several ways in which <i><b>isMultipleCall</b></i> can extend the standard MALAB functionality. First, by moving <i><b>isMultipleCall</b></i> reference from the first line of the callback we can create both an interruptible and an uninteruptible code block, e.g.</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> MyCallback<span style="color: #080;">&#40;</span>hObj, EventData<span style="color: #080;">&#41;</span>
&nbsp;
  <span style="color: #228B22;">%Code Block 1</span>
  <span style="color: #F0F;">...</span>
&nbsp;
  <span style="color: #0000FF;">if</span> isMultipleCall<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;  <span style="color: #0000FF;">return</span>;  <span style="color: #0000FF;">end</span>
&nbsp;
  <span style="color: #228B22;">%Code Block 2</span>
  <span style="color: #F0F;">...</span>
&nbsp;
  <span style="color: #0000FF;">drawnow</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>Second, as <i><b>isMultipleCall</b></i> controls the callbacks  &#8211; not the objects that trigger them &#8211; we can individually control the callbacks of objects which fire multiple events. That is particularly useful with Java components, which gives a third extension – <i><b>isMultipleCall</b></i> can be used in any function: not just the callbacks of standard MATLAB components, but also of Java or COM components.<br
/>  <br
/> Finally, as the callback, not the object is being controlled, we can control a callback that may be shared between multiple objects e.g. a menu component and a toolbar button.</p><p>Not bad for 13 lines of code.</p><p>Note: <i><b>isMultipleCall</b></i> must be called from a function, not from a string in the callback property.</p><p>Do you have any other favorite mechanism for controlling callback re-entrancy? If so, please <a
href="http://UndocumentedMatlab.com/blog/controlling-callback-re-entrancy/#respond">post a comment</a>.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/continuous-slider-callback/' rel='bookmark' title='Continuous slider callback'>Continuous slider callback</a> <small>Matlab slider uicontrols do not enable a continuous-motion callback by default. This article explains how this can be achieved using undocumented features....</small></li><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/uicontrol-callbacks/' rel='bookmark' title='Uicontrol callbacks'>Uicontrol callbacks</a> <small>This post details undocumented callbacks exposed by the underlying Java object of Matlab uicontrols, that can be used to modify the control's behavior in a multitude of different events...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/controlling-callback-re-entrancy/feed/</wfw:commentRss> <slash:comments>11</slash:comments> </item> <item><title>uisplittool &amp; uitogglesplittool callbacks</title><link>http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool-callbacks/</link> <comments>http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool-callbacks/#comments</comments> <pubDate>Wed, 15 Dec 2010 18:00:35 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Figure window]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[Hidden property]]></category> <category><![CDATA[Toolbar]]></category> <category><![CDATA[uitools]]></category> <category><![CDATA[uiundo]]></category> <category><![CDATA[Undocumented function]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=1999</guid> <description><![CDATA[Matlab's undocumented uisplittool and uitogglesplittool are powerful toolbar controls - this article explains how to customize their behavior<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool/' rel='bookmark' title='uisplittool &amp; uitogglesplittool'>uisplittool &#038; uitogglesplittool</a> <small>Matlab's undocumented uisplittool and uitogglesplittool are powerful controls that can easily be added to Matlab toolbars - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/uicontrol-callbacks/' rel='bookmark' title='Uicontrol callbacks'>Uicontrol callbacks</a> <small>This post details undocumented callbacks exposed by the underlying Java object of Matlab uicontrols, that can be used to modify the control's behavior in a multitude of different events...</small></li><li><a
href='http://undocumentedmatlab.com/blog/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></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>Last week, I presented the undocumented <i><b>uisplittool</b></i> and <i><b>uitogglesplittool</b></i> functions and showed how they can be added to a Matlab figure toolbar. Today I wish to conclude this topic by explaining how these controls can be customized with user-defined callbacks and pop-up menus.</p><h3 id="Callbacks">Callback functionality</h3><p>Both <i><b>uisplittool</b></i> and <i><b>uitogglesplittool</b></i> have a <strong>Callback</strong> property, in addition to the standard <strong>ClickedCallback</strong> property that is available in <i><b>uipushtool</b></i>s and <i><b>uitoggletool</b></i>s.</p><p>The standard <strong>ClickedCallback</strong> is invoked when the main button is clicked, while <strong>Callback</strong> is invoked when the narrow arrow button is clicked. <i><b>uitogglesplittool</b></i>, like <i><b>uitoggletool</b></i>, also has settable <strong>OnCallback</strong> and <strong>OffCallback</strong> callback properties.</p><p>The accepted convention is that <strong>ClickedCallback</strong> should invoke the default control action (in our case, an Undo/Redo of the topmost <a
target="_blank" href="http://undocumentedmatlab.com/blog/uiundo-matlab-undocumented-undo-redo-manager/">uiundo action stack</a>), while <strong>Callback</strong> should display a drop-down of selectable actions.</p><p>While this can be done programmatically using the <strong>Callback</strong> property, this functionality is already pre-built into <i><b>uisplittool</b></i> and <i><b>uitogglesplittool</b></i> for our benefit. To access it, we need to get the control&#8217;s underlying Java component.</p><p>Accessing the underlying Java component is normally done using the <a
target="_blank" href="http://undocumentedmatlab.com/blog/findjobj-find-underlying-java-object/">findjobj utility</a>, but in this case we have a shortcut: the control handle&#8217;s hidden <strong>JavaContainer</strong> property that holds the underlying <i>com.mathworks.hg.peer.SplitButtonPeer</i> (or <i>.ToggleSplitButtonPeer</i>) Java reference handle. This Java object&#8217;s <strong>MenuComponent</strong> property returns a reference to the control&#8217;s drop-down sub-component (which is a <i>com.mathworks.mwswing.MJPopupMenu</i> object):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; jUndo = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>hUndo,<span style="color:#A020F0;">'JavaContainer'</span><span style="color: #080;">&#41;</span>
jUndo =
com.<span style="">mathworks</span>.<span style="">hg</span>.<span style="">peer</span>.<span style="">SplitButtonPeer</span>@f09ad5
&nbsp;
&gt;&gt; jMenu = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>jUndo,<span style="color:#A020F0;">'MenuComponent'</span><span style="color: #080;">&#41;</span>  <span style="color: #228B22;">% or: =jUndo.getMenuComponent</span>
jMenu =
com.<span style="">mathworks</span>.<span style="">mwswing</span>.<span style="">MJPopupMenu</span><span style="color: #080;">&#91;</span>Dropdown Picker ButtonMenu,<span style="color: #F0F;">...</span><span style="color: #080;">&#93;</span></pre></div></div><p>Let&#8217;s add a few simple textual options:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jOption1 = jMenu.<span style="">add</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Option #1'</span><span style="color: #080;">&#41;</span>;
jOption1 = jMenu.<span style="">add</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Option #2'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>jOption1, <span style="color:#A020F0;">'ActionPerformedCallback'</span>, <span style="color:#A020F0;">'disp('</span><span style="color:#A020F0;">'option #1'</span><span style="color:#A020F0;">')'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>jOption2, <span style="color:#A020F0;">'ActionPerformedCallback'</span>, <span style="color: #080;">&#123;</span>@myCallbackFcn, extraData<span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 320px"><img
alt="setting uisplittool &amp; uitogglesplittool popup-menus" src="http://UndocumentedMatlab.com/images/uisplittool3.png" title="setting uisplittool &amp; uitogglesplittool popup-menus" width="99" height="72" /><p
class="wp-caption-text">setting <i><b>uisplittool</b></i> &amp; <i><b>uitogglesplittool</b></i> popup-menus</p></div></center></p><p>Popup-menus are described in more detail elsewhere (and in future articles). In the past I have already explained how icons and HTML markup can be added to menu items. Sub-menus can also be added.</p><h3 id="Example">A complete example</h3><p>Let&#8217;s now use this information, together with last year&#8217;s <a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/uiundo/">set of articles</a> about Matlab&#8217;s undocumented <i><b>uiundo</b></i> functionality, to generate a complete and more realistic example, of undo/redo toolbar buttons.</p><p>Undo and redo are actions that are particularly suited for <i><b>uisplittool</b></i>, since its main button enables us to easily undo/redo the latest action (like a simple toolbar button, by clicking the main <i><b>uisplittool</b></i> button) as well as select items from the actions drop-down (like a combo-box, by clicking the attached arrow button) – all this using a single component.</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Display our GUI</span>
hEditbox = <span style="color: #0000FF;">uicontrol</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'style'</span>,<span style="color:#A020F0;">'edit'</span>, <span style="color:#A020F0;">'position'</span>,<span style="color: #080;">&#91;</span><span style="color: #33f;">20</span>,<span style="color: #33f;">60</span>,<span style="color: #33f;">40</span>,<span style="color: #33f;">40</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>; 
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hEditbox, <span style="color:#A020F0;">'Enable'</span>,<span style="color:#A020F0;">'off'</span>, <span style="color:#A020F0;">'string'</span>,<span style="color:#A020F0;">'0'</span><span style="color: #080;">&#41;</span>;
hSlider = <span style="color: #0000FF;">uicontrol</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'style'</span>,<span style="color:#A020F0;">'slider'</span>,<span style="color:#A020F0;">'userdata'</span>,hEditbox<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hSlider,<span style="color:#A020F0;">'Callback'</span>,@test_uiundo<span style="color: #080;">&#41;</span>;  
&nbsp;
<span style="color: #228B22;">% Display the figure toolbar that was hidden by the uicontrol function</span>
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span>,<span style="color:#A020F0;">'Toolbar'</span>,<span style="color:#A020F0;">'figure'</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Add the Undo/Redo buttons</span>
hToolbar = findall<span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span>,<span style="color:#A020F0;">'tag'</span>,<span style="color:#A020F0;">'FigureToolBar'</span><span style="color: #080;">&#41;</span>;
hUndo = uisplittool<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'parent'</span>,hToolbar<span style="color: #080;">&#41;</span>;
hRedo = uitogglesplittool<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'parent'</span>,hToolbar<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Load the Redo icon</span>
icon = <span style="color: #0000FF;">fullfile</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">matlabroot</span>,<span style="color:#A020F0;">'/toolbox/matlab/icons/greenarrowicon.gif'</span><span style="color: #080;">&#41;</span>;
<span style="color: #080;">&#91;</span>cdata,map<span style="color: #080;">&#93;</span> = <span style="color: #0000FF;">imread</span><span style="color: #080;">&#40;</span>icon<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Convert white pixels into a transparent background</span>
map<span style="color: #080;">&#40;</span><span style="color: #0000FF;">find</span><span style="color: #080;">&#40;</span>map<span style="color: #080;">&#40;</span><span style="color: #F0F;">:</span>,<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>+map<span style="color: #080;">&#40;</span><span style="color: #F0F;">:</span>,<span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>+map<span style="color: #080;">&#40;</span><span style="color: #F0F;">:</span>,<span style="color: #33f;">3</span><span style="color: #080;">&#41;</span>==<span style="color: #33f;">3</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> = <span style="color: #0000FF;">NaN</span>;
&nbsp;
<span style="color: #228B22;">% Convert into 3D RGB-space</span>
cdataRedo = ind2rgb<span style="color: #080;">&#40;</span>cdata,map<span style="color: #080;">&#41;</span>;
cdataUndo = cdataRedo<span style="color: #080;">&#40;</span><span style="color: #F0F;">:</span>,<span style="color: #080;">&#91;</span><span style="color: #33f;">16</span><span style="color: #F0F;">:</span>-<span style="color: #33f;">1</span><span style="color: #F0F;">:</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>,<span style="color: #F0F;">:</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Add the icon (and its mirror image = undo) to latest toolbar</span>
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hUndo, <span style="color:#A020F0;">'cdata'</span>,cdataUndo, <span style="color:#A020F0;">'tooltip'</span>,<span style="color:#A020F0;">'undo'</span>,<span style="color:#A020F0;">'Separator'</span>,<span style="color:#A020F0;">'on'</span>, <span style="color: #F0F;">...</span>
           <span style="color:#A020F0;">'ClickedCallback'</span>,<span style="color:#A020F0;">'uiundo(gcbf,'</span><span style="color:#A020F0;">'execUndo'</span><span style="color:#A020F0;">')'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hRedo, <span style="color:#A020F0;">'cdata'</span>,cdataRedo, <span style="color:#A020F0;">'tooltip'</span>,<span style="color:#A020F0;">'redo'</span>, <span style="color: #F0F;">...</span>
           <span style="color:#A020F0;">'ClickedCallback'</span>,<span style="color:#A020F0;">'uiundo(gcbf,'</span><span style="color:#A020F0;">'execRedo'</span><span style="color:#A020F0;">')'</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Re-arrange the Undo/Redo buttons  </span>
jToolbar = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>hToolbar,<span style="color:#A020F0;">'JavaContainer'</span><span style="color: #080;">&#41;</span>,<span style="color:#A020F0;">'ComponentPeer'</span><span style="color: #080;">&#41;</span>;
jButtons = jToolbar.<span style="">getComponents</span>;
<span style="color: #0000FF;">for</span> buttonIdx = <span style="color: #0000FF;">length</span><span style="color: #080;">&#40;</span>jButtons<span style="color: #080;">&#41;</span>-<span style="color: #33f;">3</span> <span style="color: #F0F;">:</span> -<span style="color: #33f;">1</span> <span style="color: #F0F;">:</span> <span style="color: #33f;">7</span>  <span style="color: #228B22;">% end-to-front</span>
   jToolbar.<span style="">setComponentZOrder</span><span style="color: #080;">&#40;</span>jButtons<span style="color: #080;">&#40;</span>buttonIdx<span style="color: #080;">&#41;</span>, buttonIdx+<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span>
jToolbar.<span style="">setComponentZOrder</span><span style="color: #080;">&#40;</span>jButtons<span style="color: #080;">&#40;</span>end-<span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>, <span style="color: #33f;">5</span><span style="color: #080;">&#41;</span>;    <span style="color: #228B22;">% Separator</span>
jToolbar.<span style="">setComponentZOrder</span><span style="color: #080;">&#40;</span>jButtons<span style="color: #080;">&#40;</span>end-<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>, <span style="color: #33f;">6</span><span style="color: #080;">&#41;</span>;    <span style="color: #228B22;">% Undo</span>
jToolbar.<span style="">setComponentZOrder</span><span style="color: #080;">&#40;</span>jButtons<span style="color: #080;">&#40;</span><span style="color: #0000FF;">end</span><span style="color: #080;">&#41;</span>, <span style="color: #33f;">7</span><span style="color: #080;">&#41;</span>;      <span style="color: #228B22;">% Redo</span>
jToolbar.<span style="">revalidate</span>;
&nbsp;
<span style="color: #228B22;">% Retrieve redo/undo object</span>
undoObj = <span style="color: #0000FF;">getappdata</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span>,<span style="color:#A020F0;">'uitools_FigureToolManager'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">if</span> <span style="color: #0000FF;">isempty</span><span style="color: #080;">&#40;</span>undoObj<span style="color: #080;">&#41;</span>
   undoObj = uitools.<span style="">FigureToolManager</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span>;
   <span style="color: #0000FF;">setappdata</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span>,<span style="color:#A020F0;">'uitools_FigureToolManager'</span>,undoObj<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span>
&nbsp;
<span style="color: #228B22;">% Populate Undo actions drop-down list</span>
jUndo = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>hUndo,<span style="color:#A020F0;">'JavaContainer'</span><span style="color: #080;">&#41;</span>;
jMenu = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>jUndo,<span style="color:#A020F0;">'MenuComponent'</span><span style="color: #080;">&#41;</span>;
undoActions = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>undoObj.<span style="">CommandManager</span>.<span style="">UndoStack</span>,<span style="color:#A020F0;">'Name'</span><span style="color: #080;">&#41;</span>;
jMenu.<span style="">removeAll</span>;
<span style="color: #0000FF;">for</span> actionIdx = <span style="color: #0000FF;">length</span><span style="color: #080;">&#40;</span>undoActions<span style="color: #080;">&#41;</span> <span style="color: #F0F;">:</span> -<span style="color: #33f;">1</span> <span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>    <span style="color: #228B22;">% end-to-front</span>
    jActionItem = jMenu.<span style="">add</span><span style="color: #080;">&#40;</span>undoActions<span style="color: #080;">&#40;</span>actionIdx<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>jActionItem, <span style="color:#A020F0;">'ActionPerformedCallback'</span>, @myUndoCallbackFcn<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span>
jToolbar.<span style="">revalidate</span>;
&nbsp;
<span style="color: #228B22;">% Drop-down callback function</span>
<span style="color: #0000FF;">function</span> myUndoCallbackFcn<span style="color: #080;">&#40;</span>jActionItem,hEvent<span style="color: #080;">&#41;</span>
    <span style="color: #228B22;">% user processing needs to be placed here</span>
<span style="color: #0000FF;">end</span>  <span style="color: #228B22;">% myUndoCallbackFcn</span></pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 405px"><img
alt="undo/redo buttons implemented using uisplittool" src="http://UndocumentedMatlab.com/images/uisplittool4b.png" title="undo/redo buttons implemented using uisplittool" width="395" height="257" /><p
class="wp-caption-text">undo/redo buttons implemented using <i><b>uisplittool</b></i></p></div></center></p><p>In a real-world application, the code-segment above that populated the drop-down list would be placed within the slider&#8217;s <em>test_uiundo()</em> callback function, and we would set a similar drop-down for the hRedu button. In addition, we would dynamically modify the button tooltips. As a final customization, we could modify the figure&#8217;s main menu. Menu customization will be discussed in a future separate set of articles.</p><p>Have you used <i><b>uisplittool</b></i> or <i><b>uitogglesplittool</b></i> in your GUI? If so, please tell us what use you have made of them, in a comment <a
href="http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool-callbacks/#respond">below</a>.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool/' rel='bookmark' title='uisplittool &amp; uitogglesplittool'>uisplittool &#038; uitogglesplittool</a> <small>Matlab's undocumented uisplittool and uitogglesplittool are powerful controls that can easily be added to Matlab toolbars - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/uicontrol-callbacks/' rel='bookmark' title='Uicontrol callbacks'>Uicontrol callbacks</a> <small>This post details undocumented callbacks exposed by the underlying Java object of Matlab uicontrols, that can be used to modify the control's behavior in a multitude of different events...</small></li><li><a
href='http://undocumentedmatlab.com/blog/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></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool-callbacks/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Matlab callbacks for Java events</title><link>http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/</link> <comments>http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/#comments</comments> <pubDate>Tue, 30 Nov 2010 22:09:35 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[High risk of breaking in future versions]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Listeners]]></category> <category><![CDATA[Semi-documented function]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Undocumented function]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[Listener]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=1987</guid> <description><![CDATA[Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/udd-events-and-listeners/' rel='bookmark' title='UDD Events and Listeners'>UDD Events and Listeners</a> <small>UDD event listeners can be used to listen to property value changes and other important events of Matlab objects...</small></li><li><a
href='http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool-callbacks/' rel='bookmark' title='uisplittool &amp; uitogglesplittool callbacks'>uisplittool &#038; 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='http://undocumentedmatlab.com/blog/udd-and-java/' rel='bookmark' title='UDD and Java'>UDD and Java</a> <small>UDD provides built-in convenience methods to facilitate the integration of Matlab UDD objects with Java code - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/uicontrol-callbacks/' rel='bookmark' title='Uicontrol callbacks'>Uicontrol callbacks</a> <small>This post details undocumented callbacks exposed by the underlying Java object of Matlab uicontrols, that can be used to modify the control's behavior in a multitude of different events...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>A few days ago, a user <a
target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/4291769/how-do-i-notify-a-matlab-object-of-an-event-in-a-java-object">posted a question</a> on StackOverflow asking whether it is possible to trap a Java-based event in a Matlab callback.</p><p>It so happens that only a few weeks ago I completed a consulting project which required exactly this. The project was to integrate a Matlab computational engine with a Java interface to <a
target="_blank" rel="nofollow" href="http://www.interactivebrokers.com/">Interactive Brokers</a> (IB) &#8211; a well-known online brokerage firm. The idea was to use the Java interface to fetch real-time data about securities (stocks, bonds, options etc.), use a Matlab processing utility, then use the Java interface again to send Buy or Sell orders back to IB.</p><p>If you are interested in the final result (i.e., a complete and field-tested Matlab-IB interface), <a
target="_blank" href="http://undocumentedmatlab.com/ib-matlab/">look here</a>.</p><h3 id="challenge">The challenge</h3><p>A big challenge in this project (aside from handling quite a few IB interface quirks), was to propagate events from the Java interface to the Matlab application. This had to be done asynchronously, since events such as order execution can occur at any time following the order placement. Moreover, even simple requests such as retrieving security information (bid/ask prices for example) is handled by IB via Java events, not as simple function return values.</p><p>Handling Java-based events in Matlab is not a trivial task. Not only merely undocumented, but it is also not intuitive. I have spent quite a few hours trying to crack this issue. In fact, I believe it was one of my more challenging tasks in figuring out the undocumented aspects of the Matlab-Java interface. Few other challenges were as difficult, yet with a happy ending (Drag &#038; Drop is a similar issue &#8211; I will describe it in another article sometime).</p><h3 id="solution">The solution</h3><p>Fast-forward all the fruitless attempted variations, here is the bottom line. Refer to the following simple Java class example:</p><div
class="wp_syntax"><div
class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> EventTest
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> java.<span style="color: #006633;">util</span>.<span style="color: #003399;">Vector</span> data <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> java.<span style="color: #006633;">util</span>.<span style="color: #003399;">Vector</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #000066; font-weight: bold;">void</span> addMyTestListener<span style="color: #009900;">&#40;</span>MyTestListener lis<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        data.<span style="color: #006633;">addElement</span><span style="color: #009900;">&#40;</span>lis<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #000066; font-weight: bold;">void</span> removeMyTestListener<span style="color: #009900;">&#40;</span>MyTestListener lis<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        data.<span style="color: #006633;">removeElement</span><span style="color: #009900;">&#40;</span>lis<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> MyTestListener <span style="color: #000000; font-weight: bold;">extends</span> java.<span style="color: #006633;">util</span>.<span style="color: #003399;">EventListener</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">void</span> testEvent<span style="color: #009900;">&#40;</span>MyTestEvent event<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MyTestEvent <span style="color: #000000; font-weight: bold;">extends</span> java.<span style="color: #006633;">util</span>.<span style="color: #003399;">EventObject</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">long</span> serialVersionUID <span style="color: #339933;">=</span> 1L<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">float</span> oldValue,newValue<span style="color: #339933;">;</span>        
        MyTestEvent<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> obj, <span style="color: #000066; font-weight: bold;">float</span> oldValue, <span style="color: #000066; font-weight: bold;">float</span> newValue<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span>obj<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">oldValue</span> <span style="color: #339933;">=</span> oldValue<span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">newValue</span> <span style="color: #339933;">=</span> newValue<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> notifyMyTest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        java.<span style="color: #006633;">util</span>.<span style="color: #003399;">Vector</span> dataCopy<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">synchronized</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            dataCopy <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>java.<span style="color: #006633;">util</span>.<span style="color: #003399;">Vector</span><span style="color: #009900;">&#41;</span>data.<span style="color: #006633;">clone</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i<span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span>dataCopy.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            MyTestEvent event <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyTestEvent<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>MyTestListener<span style="color: #009900;">&#41;</span>dataCopy.<span style="color: #006633;">elementAt</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">testEvent</span><span style="color: #009900;">&#40;</span>event<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div><p>When compiling EventTest.java, three class files are created: EventTest.class, EventTest$MyTestEvent.class and EventTest$MyTestListener.class. Place them on Matlab&#8217;s Java static classpath, using <i><b>edit</b>(&#8216;classpath.txt&#8217;)</i> (using the dynamic classpath causes many problems that using the static classpath solves). They can now be accessed as follows:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">which</span> EventTest
EventTest <span style="color: #0000FF;">is</span> a Java method  <span style="color: #228B22;">% EventTest constructor</span>
&nbsp;
&gt;&gt; evt = EventTest
evt =
EventTest@16166fc
&nbsp;
&gt;&gt; evt.<span style="color: #0000FF;">get</span>
	<span style="color: #0000FF;">Class</span> = <span style="color: #080;">&#91;</span> <span style="color: #080;">&#40;</span><span style="color: #33f;">1</span> by <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> java.<span style="">lang</span>.<span style="color: #0000FF;">Class</span> array<span style="color: #080;">&#93;</span>
	TestEventCallback = 
	TestEventCallbackData = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
&nbsp;
	BeingDeleted = off
	ButtonDownFcn = 
	Children = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
	Clipping = on
	CreateFcn = 
	DeleteFcn = 
	BusyAction = queue
	HandleVisibility = on
	HitTest = on
	Interruptible = on
	Parent = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
	Selected = off
	SelectionHighlight = on
	Tag = 
	<span style="color: #0000FF;">Type</span> = EventTest
	<span style="color: #0000FF;">UIContextMenu</span> = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
	UserData = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
	Visible = on
&nbsp;
&gt;&gt; <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>evt<span style="color: #080;">&#41;</span>
	<span style="color: #0000FF;">Class</span>
	TestEventCallback<span style="color: #F0F;">:</span> string -or- <span style="color: #0000FF;">function</span> handle -or- <span style="color: #0000FF;">cell</span> array
	<span style="color: #F0F;">...</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>evt,<span style="color:#A020F0;">'TestEventCallback'</span>,@<span style="color: #080;">&#40;</span>h,e<span style="color: #080;">&#41;</span><span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>h<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>evt<span style="color: #080;">&#41;</span>
	<span style="color: #0000FF;">Class</span> = <span style="color: #080;">&#91;</span> <span style="color: #080;">&#40;</span><span style="color: #33f;">1</span> by <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> java.<span style="">lang</span>.<span style="color: #0000FF;">Class</span> array<span style="color: #080;">&#93;</span>
	TestEventCallback = <span style="color: #080;">&#91;</span> <span style="color: #080;">&#40;</span><span style="color: #33f;">1</span> by <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> function_handle array<span style="color: #080;">&#93;</span>   &lt;= ok
	TestEventCallbackData = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
	<span style="color: #F0F;">...</span>
&nbsp;
&gt;&gt; evt.<span style="">notifyMyTest</span>   <span style="color: #228B22;">% invoke Java event</span>
              <span style="color: #33f;">0.0009765625</span>   <span style="color: #228B22;">% &lt;= Matlab callback</span></pre></div></div><p>Note how Matlab automatically converted the Java event testEvent, declared in interface MyTestListener, into a Matlab callback TestEventCallback (the first character is always capitalized). All Java events are automatically converted in this fashion, by appending a &#8216;Callback&#8217; suffix. Here is a code snippet from R2008a&#8217;s \toolbox\matlab\uitools\@opaque\addlistener.m that shows this (slightly edited):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">hSrc = handle<span style="color: #080;">&#40;</span>jobj,<span style="color:#A020F0;">'callbackproperties'</span><span style="color: #080;">&#41;</span>;
allfields = <span style="color: #0000FF;">sortrows</span><span style="color: #080;">&#40;</span>fields<span style="color: #080;">&#40;</span><span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hSrc<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">for</span> <span style="color: #0000FF;"><span style="color: #33f;">i</span></span> = <span style="color: #33f;">1</span><span style="color: #F0F;">:</span><span style="color: #0000FF;">length</span><span style="color: #080;">&#40;</span>allfields<span style="color: #080;">&#41;</span>
   fn = allfields<span style="color: #080;">&#123;</span><span style="color: #0000FF;"><span style="color: #33f;">i</span></span><span style="color: #080;">&#125;</span>;
   <span style="color: #0000FF;">if</span> ~<span style="color: #0000FF;">isempty</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">findstr</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Callback'</span>,fn<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
      <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">strrep</span><span style="color: #080;">&#40;</span>fn,<span style="color:#A020F0;">'Callback'</span>,<span style="color:#A020F0;">''</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
   <span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">end</span>
&nbsp;
callback = @<span style="color: #080;">&#40;</span>o,e<span style="color: #080;">&#41;</span> cbBridge<span style="color: #080;">&#40;</span>o,e,response<span style="color: #080;">&#41;</span>;
hdl = <span style="color: #0000FF;">handle.<span style="">listener</span></span><span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span>jobj<span style="color: #080;">&#41;</span>, eventName, callback<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">function</span> cbBridge<span style="color: #080;">&#40;</span>o,e,response<span style="color: #080;">&#41;</span>
   hgfeval<span style="color: #080;">&#40;</span>response, java<span style="color: #080;">&#40;</span>o<span style="color: #080;">&#41;</span>, e.<span style="">JavaEvent</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">end</span></pre></div></div><p>Note that <i><b>hgfeval</b></i>, which is used within the cbBridge callback function, is a semi-documented pure-Matlab built-in function, which I <a
target="_blank" href="http://UndocumentedMatlab.com/blog/hgfeval/">described</a> a few weeks ago.</p><p>If several events have the same case-insensitive name, then the additional callbacks will have an appended underscore character (e.g., &#8216;TestEventCallback_&#8217;):</p><div
class="wp_syntax"><div
class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// In the Java class:</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> MyTestListener <span style="color: #000000; font-weight: bold;">extends</span> java.<span style="color: #006633;">util</span>.<span style="color: #003399;">EventListener</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">void</span> testEvent<span style="color: #009900;">&#40;</span>MyTestEvent e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">void</span> testevent<span style="color: #009900;">&#40;</span>TestEvent2 e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% …and back in Matlab:</span>
&gt;&gt; evt=EventTest; evt.<span style="color: #0000FF;">get</span>
	<span style="color: #0000FF;">Class</span> = <span style="color: #080;">&#91;</span> <span style="color: #080;">&#40;</span><span style="color: #33f;">1</span> by <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> java.<span style="">lang</span>.<span style="color: #0000FF;">Class</span> array<span style="color: #080;">&#93;</span>
	TestEventCallback = 
	TestEventCallbackData = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
	TestEventCallback_ = 
	TestEventCallback_Data = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span> 
	<span style="color: #F0F;">...</span></pre></div></div><p>To complete this discussion, it should be noted that Matlab also automatically defines corresponding Events in the Java object’s <i><b>classhandle</b></i>. Unfortunately, <i><b>classhandle</b></i> events are not differentiated in a similar manner – in this case only a single event is created, named Testevent. <i><b>classhandle</b></i> events, and their relationship to the preceding discussion, will be described in Donn Scull&#8217;s upcoming series on UDD.</p><p>An alternative to using callbacks on Java events, as shown above, is to use undocumented <a
target="_blank" href="http://UndocumentedMatlab.com/blog/continuous-slider-callback/#Event_Listener"><i><b>handle.listener</b></i>s</a>:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">hListener = <span style="color: #0000FF;">handle.<span style="">listener</span></span><span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span>evt<span style="color: #080;">&#41;</span>,<span style="color:#A020F0;">'TestEvent'</span>,callback<span style="color: #080;">&#41;</span>;</pre></div></div><p>There are several other odds and ends, but this article should be sufficient for implementing a fully-functional Java event handling mechanism in Matlab. Good luck!</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/udd-events-and-listeners/' rel='bookmark' title='UDD Events and Listeners'>UDD Events and Listeners</a> <small>UDD event listeners can be used to listen to property value changes and other important events of Matlab objects...</small></li><li><a
href='http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool-callbacks/' rel='bookmark' title='uisplittool &amp; uitogglesplittool callbacks'>uisplittool &#038; 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='http://undocumentedmatlab.com/blog/udd-and-java/' rel='bookmark' title='UDD and Java'>UDD and Java</a> <small>UDD provides built-in convenience methods to facilitate the integration of Matlab UDD objects with Java code - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/uicontrol-callbacks/' rel='bookmark' title='Uicontrol callbacks'>Uicontrol callbacks</a> <small>This post details undocumented callbacks exposed by the underlying Java object of Matlab uicontrols, that can be used to modify the control's behavior in a multitude of different events...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/feed/</wfw:commentRss> <slash:comments>27</slash:comments> </item> <item><title>The hgfeval function</title><link>http://undocumentedmatlab.com/blog/hgfeval/</link> <comments>http://undocumentedmatlab.com/blog/hgfeval/#comments</comments> <pubDate>Wed, 27 Oct 2010 18:00:59 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Semi-documented function]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[Pure Matlab]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=1925</guid> <description><![CDATA[The semi-documented hgfeval function can be useful for callback chaining - this article explains how<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/javacomponent/' rel='bookmark' title='The javacomponent function'>The javacomponent function</a> <small>Matlab's built-in javacomponent function can be used to display Java components in Matlab application - this article details its usages and limitations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/undocumented-feature-function/' rel='bookmark' title='Undocumented feature() function'>Undocumented feature() function</a> <small>Matlab's undocumented feature function enables access to some internal experimental features...</small></li><li><a
href='http://undocumentedmatlab.com/blog/ismembc-undocumented-helper-function/' rel='bookmark' title='ismembc &#8211; undocumented helper function'>ismembc &#8211; undocumented helper function</a> <small>Matlab has several undocumented internal helper functions that can be useful on their own in some cases. This post presents the ismembc function....</small></li><li><a
href='http://undocumentedmatlab.com/blog/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></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>Last week&#8217;s article about <a
target="_blank" href="http://UndocumentedMatlab.com/blog/matlab-java-interface-using-static-control/">using a static GUI control</a>, made use of the <i><b>hgfeval</b></i> function for its callback switch-yard dispatching. Today&#8217;s article will expose this important but often overlooked function.</p><p><i><b>hgfeval</b></i> is a built-in <a
target="_blank" href="http://UndocumentedMatlab.com/blog/legend-semi-documented-feature/#Semi-documented">semi-documented</a> function. This means that the function is explained in a comment within the hgfeval.m file (which can be seen via the <i><b>edit</b></i>(&#8216;hgfeval&#8217;) command), that is nonetheless not part of the official help or doc sections. It is an unsupported function originally intended only for internal Matlab use, which of course doesn&#8217;t mean we can&#8217;t use it. <i><b>hgfeval</b></i> is currently used extensively within the Matlab code-base.</p><h3 id="Chaining">Callback chaining</h3><p><i><b>hgfeval</b></i>&#8216;s main purpose is to programmatically (synchronously) invoke a callback, rather than it being dynamically (a-synchronously) invoked when some event occurs. This need often occurs when <a
target="_blank" href="http://UndocumentedMatlab.com/blog/inactive-control-tooltips-event-chaining/">chaining events</a>. In a nutshell, we need to programmatically invoke Callback A (an executable code [=string], function handle, or cell array of function handle with extra parameters) within our code, which is typically located in another callback (B). For example:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> CallbackB<span style="color: #080;">&#40;</span>hObject, hEventData, <span style="color: #0000FF;">varargin</span><span style="color: #080;">&#41;</span>
    callbackA = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span>, <span style="color:#A020F0;">'ButtonDownFcn'</span><span style="color: #080;">&#41;</span>;
    hgfeval<span style="color: #080;">&#40;</span>callbackA<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p><i><b>hgfeval</b></i> is important when we want to force the objects passed as the callback&#8217;s first two input parameters (hObject and hEventData): <i><b>hgfeval</b></i> pre-pends all its extra parameters (arguments #2+) to the callback&#8217;ed function. So, calling <i><b>hgfeval</b></i>({@myFunc,arg1,arg2}, argA, argB) will actually invoke <i>myFunc</i>(argA,argB,arg1,arg2). Using this syntax we guaranty that whatever the invoked callback may be, its initial arguments will always be set to the necessary argA,argB.</p><p>This is often used in what MathWorks calls a callback-bridge. For example, in the following example we set the cbBridge function as a callback bridge for myCallback, that forces <i><b>java</b></i>(o) as the reference object (the invoked callback&#8217;s first argument) and e.JavaEvent as the second arg; all user args will then follow as optional additional args:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">hdl = <span style="color: #0000FF;">handle.<span style="">listener</span></span><span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span>jobj<span style="color: #080;">&#41;</span>, eventName, <span style="color: #F0F;">...</span>
                      @<span style="color: #080;">&#40;</span>o,e<span style="color: #080;">&#41;</span>cbBridge<span style="color: #080;">&#40;</span>o,e,@myCallback<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">function</span> cbBridge<span style="color: #080;">&#40;</span>o,e,myCallback<span style="color: #080;">&#41;</span>
    hgfeval<span style="color: #080;">&#40;</span>myCallback, java<span style="color: #080;">&#40;</span>o<span style="color: #080;">&#41;</span>, e.<span style="">JavaEvent</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">end</span></pre></div></div><p>If we had used myCallback directly, then myCallback would have been invoked with o and e rather than <i><b>java</b></i>(o) and e.JavaEvent. The point here is that using the callback bridge and <i><b>hgfeval</b></i> enabled us to tailor the parameters passed to the callback function.</p><h3 id="Compatibility">Forward &#038; backward compatibility</h3><p><i><b>hgfeval</b></i> has been built-in within all standard Matlab 7 releases, so while it may be discontinued in some future Matlab release, it did have a very long life span.</p><p>Even if for some reason this function is removed in some future Matlab release, it can easily be reproduced &#8211; after all, it only contains 35 very simple lines of pure Matlab code. In fact, for some project that had to rely on Matlab 6 (in which <i><b>hgfeval</b></i> was not yet available), it was an almost trivial task to retrofit an <i><b>hgfeval</b></i> look-alike (I had to remove function handles and similar minor tweaks):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">%% hgfeval replacement for Matlab 6 compatibility</span>
<span style="color: #0000FF;">function</span> hgfeval<span style="color: #080;">&#40;</span>fcn,<span style="color: #0000FF;">varargin</span><span style="color: #080;">&#41;</span>
    <span style="color: #0000FF;">if</span> <span style="color: #0000FF;">isempty</span><span style="color: #080;">&#40;</span>fcn<span style="color: #080;">&#41;</span>,  <span style="color: #0000FF;">return</span>;  <span style="color: #0000FF;">end</span>
    <span style="color: #0000FF;">if</span> iscell<span style="color: #080;">&#40;</span>fcn<span style="color: #080;">&#41;</span>
        <span style="color: #0000FF;">feval</span><span style="color: #080;">&#40;</span>fcn<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span>,<span style="color: #0000FF;">varargin</span><span style="color: #080;">&#123;</span><span style="color: #F0F;">:</span><span style="color: #080;">&#125;</span>,fcn<span style="color: #080;">&#123;</span><span style="color: #33f;">2</span><span style="color: #F0F;">:</span><span style="color: #0000FF;">end</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">elseif</span> <span style="color: #0000FF;">ischar</span><span style="color: #080;">&#40;</span>fcn<span style="color: #080;">&#41;</span>
        <span style="color: #0000FF;">evalin</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'base'</span>, fcn<span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">else</span>
        <span style="color: #0000FF;">feval</span><span style="color: #080;">&#40;</span>fcn,<span style="color: #0000FF;">varargin</span><span style="color: #080;">&#123;</span><span style="color: #F0F;">:</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">end</span>
<span style="color: #228B22;">%end  %no function end in Matlab 6...</span></pre></div></div><p>Have you ever used <i><b>hgfeval</b></i> in your code? If so, please share your experience in a comment <a
target="_blank" href="http://UndocumentedMatlab.com/blog/hgfeval/#respond">below</a>.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/javacomponent/' rel='bookmark' title='The javacomponent function'>The javacomponent function</a> <small>Matlab's built-in javacomponent function can be used to display Java components in Matlab application - this article details its usages and limitations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/undocumented-feature-function/' rel='bookmark' title='Undocumented feature() function'>Undocumented feature() function</a> <small>Matlab's undocumented feature function enables access to some internal experimental features...</small></li><li><a
href='http://undocumentedmatlab.com/blog/ismembc-undocumented-helper-function/' rel='bookmark' title='ismembc &#8211; undocumented helper function'>ismembc &#8211; undocumented helper function</a> <small>Matlab has several undocumented internal helper functions that can be useful on their own in some cases. This post presents the ismembc function....</small></li><li><a
href='http://undocumentedmatlab.com/blog/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></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/hgfeval/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Matlab-Java interface using a static control</title><link>http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/</link> <comments>http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/#comments</comments> <pubDate>Wed, 13 Oct 2010 18:15:43 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Guest bloggers]]></category> <category><![CDATA[GUI]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[Karthik Ponudurai]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=1917</guid> <description><![CDATA[The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/inactive-control-tooltips-event-chaining/' rel='bookmark' title='Inactive Control Tooltips &amp; Event Chaining'>Inactive Control Tooltips &#038; Event Chaining</a> <small>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....</small></li><li><a
href='http://undocumentedmatlab.com/blog/gui-integrated-browser-control/' rel='bookmark' title='GUI integrated browser control'>GUI integrated browser control</a> <small>A fully-capable browser component is included in Matlab and can easily be incorporated in regular Matlab GUI applications. This article shows how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/using-java-collections-in-matlab/' rel='bookmark' title='Using Java Collections in Matlab'>Using Java Collections in Matlab</a> <small>Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how. ...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><i>I would like to welcome guest blogger Karthik Ponudurai. Today, Karthik will introduce an interesting technique for interfacing Java GUI to a Matlab application.</i></p><p>The current method of interfacing Java GUI controls and Matlab is by retrieving the underlying Java callback and assigning it to a Matlab callback, as shown in the following example:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Create a Java button</span>
jButton = javacomponent<span style="color: #080;">&#40;</span>javax.<span style="">swing</span>.<span style="">JButton</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'click me'</span><span style="color: #080;">&#41;</span>, <span style="color: #F0F;">...</span>
                        <span style="color: #080;">&#91;</span><span style="color: #33f;">20</span>,<span style="color: #33f;">20</span>,<span style="color: #33f;">60</span>,<span style="color: #33f;">20</span><span style="color: #080;">&#93;</span>, <span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Assign a Matlab callback</span>
hButton = handle<span style="color: #080;">&#40;</span>jButton, <span style="color:#A020F0;">'CallbackProperties'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>jButton, <span style="color:#A020F0;">'ActionPerformedCallback'</span>, @myCallback<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Matlab callback function</span>
<span style="color: #0000FF;">function</span> myCallback<span style="color: #080;">&#40;</span>hObject, hEventData<span style="color: #080;">&#41;</span>
    <span style="color: #228B22;">% Insert your code here</span>
<span style="color: #0000FF;">end</span></pre></div></div><p>This approach works fine for simple pure-Java GUI created using an IDE (for example, <a
target="_blank" rel="nofollow" href="http://netbeans.org/">NetBeans</a> or <a
target="_blank" rel="nofollow" href="http://eclipse.org/">Eclipse</a>) that only have a small number of controls. You can retrieve all the Java controls in Matlab and set the callbacks as shown in the above example.</p><p>Unfortunately, practical GUIs often contain numerous controls. Assigning each control a different Matlab callback can be quite tedious.</p><h3 id="">Using a callback switchyard function</h3><p>A workaround to this problem can be achieved using an invisible/hidden static Java JButton. During Matlab initialization, assign a single callback for the static Java JButton:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Return a reference to the GUI's static trigger button</span>
triggerButton = statictrigger.<span style="">triggerCls</span>.<span style="">getTrigger</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Assign Matlab switchyard callback for triggerButton</span>
buttonProps = handle<span style="color: #080;">&#40;</span>triggerButton, <span style="color:#A020F0;">'callbackproperties'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>triggerButton, <span style="color:#A020F0;">'ActionPerformedCallback'</span>,@TriggerCallback<span style="color: #080;">&#41;</span>;</pre></div></div><p>When an event is triggered by any monitored control in the Java GUI, then within the Java code set the static button&#8217;s action command string to the desired Matlab callback name (a String) and invoke the static button&#8217;s <i>doClick()</i> method to trigger the Matlab TriggerCallback callback. Based on the action command string, this callback invokes the appropriate Matlab function. In this manner, Matlab&#8217;s TriggerCallback() acts as a <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/company/newsletters/news_notes/win00/prog_patterns.html">switchyard function</a> to the actual callback functions:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> TriggerCallback<span style="color: #080;">&#40;</span>hObject, hEventData<span style="color: #080;">&#41;</span>
   actionCmd = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span> hObject.<span style="">getActionCommand</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#41;</span>;
   hgfeval<span style="color: #080;">&#40;</span>actionCmd, hObject, hEventData<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>Note how the <i><b>char</b></i> function converts the Java action command (a java.lang.String object) into Matlab char array. The requested Matlab function is then dynamically invoked using Matlab&#8217;s semi-documented <a
target="_blank" href="http://undocumentedmatlab.com/blog/hgfeval/"><i><b>hgfeval</b></i> function</a>, which Yair will describe in another article later this month.</p><p>The next few sections will look into the sample application in more detail. This application can be downloaded from <a
target="_blank" href="http://UndocumentedMatlab.com/files/StaticButtonTrigger.zip">here</a>.</p><h3 id="GUI">Java GUI</h3><p>Firstly, let&#8217;s look into the Java GUI:<br
/><center><div
class="wp-caption aligncenter" style="width: 418px"><img
alt="Main Java GUI" src="http://UndocumentedMatlab.com/images/StaticButton_Java_Frame.png" title="Main Java GUI" width="408" height="325" /><p
class="wp-caption-text">Main Java GUI</p></div></center></p><p>When the &#8220;Show Result in Matlab Dialog Box&#8221; button is clicked, the form information&#8217;s (Name, Age, Sex etc&#8230;) is saved in a hash map. This hash map is then serialized to a local file (C:\streamdata). Next, the static button&#8217;s action command string is set to &#8216;show&#8217; and finally its <i>doClick()</i> method is invoked.</p><p>Below is the Java code corresponding to button click event:</p><div
class="wp_syntax"><div
class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> showActionPerformed<span style="color: #009900;">&#40;</span>java.<span style="color: #006633;">awt</span>.<span style="color: #006633;">event</span>.<span style="color: #003399;">ActionEvent</span> evt<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Add form values to hash map</span>
    hMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>name.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, name.<span style="color: #006633;">getText</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    hMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>age.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, age.<span style="color: #006633;">getValue</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    hMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>sex.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#41;</span>sex.<span style="color: #006633;">getSelectedItem</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    hMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>address.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, address.<span style="color: #006633;">getText</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    hMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>email.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, email.<span style="color: #006633;">getText</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Serialize hash map</span>
    WriteObject<span style="color: #009900;">&#40;</span>hMap<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Set trigger</span>
    triggerCls.<span style="color: #006633;">setTrigger</span><span style="color: #009900;">&#40;</span>evt.<span style="color: #006633;">getActionCommand</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div><h3 id="Matlab">Matlab callbacks</h3><p>The Java GUI sources are compiled and packaged in the statictrigger.jar file. The Matlab StaticButtonTriggerExample.m source file adds the Java library to the dynamic Java classpath:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Add dynamic java class path</span>
javaclasspath<span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span><span style="color: #0000FF;">pwd</span> <span style="color:#A020F0;">'\javalib\statictrigger.jar'</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>The main.m function contains the code for creating the Java GUI and assigning the static button callback:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% create the statictrigger object</span>
app = statictrigger.<span style="">app</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Set static trigger button listener</span>
triggerButton = statictrigger.<span style="">triggerCls</span>.<span style="">getTrigger</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
buttonProps = handle<span style="color: #080;">&#40;</span>triggerButton,<span style="color:#A020F0;">'callbackproperties'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>buttonProps,<span style="color:#A020F0;">'ActionPerformedCallback'</span>, <span style="color: #080;">&#123;</span>@StaticButtonTriggerCallback, app<span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>; 
&nbsp;
<span style="color: #228B22;">% Show the Java Frame </span>
app.<span style="">setVisible</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>statictrigger.triggerCls.<i>getTrigger()</i> is a static Java public method that returns the static button object, for which we assign our callback switchyard function.</p><p>The following is the StaticButtonTriggerCallback.m code, which displays the information in a Matlab message-box:<br
/><center><div
class="wp-caption aligncenter" style="width: 409px"><img
alt="Matlab message-box triggered by the Java GUI" src="http://UndocumentedMatlab.com/images/StaticButton_Matlab_Msgbox.png" title="Matlab message-box triggered by the Java GUI" width="399" height="133" /><p
class="wp-caption-text">Matlab message-box triggered by the Java GUI</p></div></center></p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Get action command string  </span>
actionCommand = src.<span style="">getActionCommand</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Read in serialized hash map</span>
hashMap = app.<span style="">ReadObject</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Convert hash map to Matlab structure     </span>
data = Hash2Struct<span style="color: #080;">&#40;</span>hashMap<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Display data in Matlab dialog box</span>
msg = <span style="color: #080;">&#91;</span><span style="color:#A020F0;">'Name: '</span> <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>hashMap.<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'name'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #F0F;">...</span>
       <span style="color:#A020F0;">', Age: '</span> <span style="color: #0000FF;">num2str</span><span style="color: #080;">&#40;</span>hashMap.<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'age'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #F0F;">...</span>
       <span style="color:#A020F0;">', Sex: '</span> <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>hashMap.<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'sex'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #F0F;">...</span>
       <span style="color:#A020F0;">', Address: '</span> <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>hashMap.<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'address'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #F0F;">...</span>
       <span style="color:#A020F0;">', Email: '</span> <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>hashMap.<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'email'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#93;</span>;
uiwait<span style="color: #080;">&#40;</span><span style="color: #0000FF;">helpdlg</span><span style="color: #080;">&#40;</span>msg, <span style="color:#A020F0;">'Form Details'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>You can download the example&#8217;s files from <a
target="_blank" href="http://UndocumentedMatlab.com/files/StaticButtonTrigger.zip">here</a>. Extract the zip file, <i><b>cd</b></i> to the newly-generated StaticButtonTrigger folder, then invoke the StaticButtonTriggerExample.m function to run the example.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/inactive-control-tooltips-event-chaining/' rel='bookmark' title='Inactive Control Tooltips &amp; Event Chaining'>Inactive Control Tooltips &#038; Event Chaining</a> <small>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....</small></li><li><a
href='http://undocumentedmatlab.com/blog/gui-integrated-browser-control/' rel='bookmark' title='GUI integrated browser control'>GUI integrated browser control</a> <small>A fully-capable browser component is included in Matlab and can easily be incorporated in regular Matlab GUI applications. This article shows how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/using-java-collections-in-matlab/' rel='bookmark' title='Using Java Collections in Matlab'>Using Java Collections in Matlab</a> <small>Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how. ...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/feed/</wfw:commentRss> <slash:comments>17</slash:comments> </item> <item><title>Accessing plot brushed data</title><link>http://undocumentedmatlab.com/blog/accessing-plot-brushed-data/</link> <comments>http://undocumentedmatlab.com/blog/accessing-plot-brushed-data/#comments</comments> <pubDate>Wed, 06 Oct 2010 18:00:45 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <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[Plot data brushing can be accessed programmatically using very simple pure-Matlab code<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/accessing-the-matlab-editor/' rel='bookmark' title='Accessing the Matlab Editor'>Accessing the Matlab Editor</a> <small>The Matlab Editor can be accessed programmatically, for a wide variety of possible uses - this article shows how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/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><li><a
href='http://undocumentedmatlab.com/blog/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...</small></li></ol><pre> </pre>]]></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.</p><p><center><div
class="wp-caption aligncenter" style="width: 460px"><img
alt="Saving brushed data to a variable" src="http://UndocumentedMatlab.com/images/Brushing1b.png" title="Saving brushed data to a variable" width="450" height="325" /><p
class="wp-caption-text">Saving brushed data to a variable</p></div></center></p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">t=<span style="color: #33f;">0</span><span style="color: #F0F;">:</span><span style="color: #33f;">0.2</span><span style="color: #F0F;">:</span><span style="color: #33f;">25</span>; <span style="color: #0000FF;">plot</span><span style="color: #080;">&#40;</span>t,<span style="color: #0000FF;">sin</span><span style="color: #080;">&#40;</span>t<span style="color: #080;">&#41;</span>,<span style="color:#A020F0;">'.-'</span><span style="color: #080;">&#41;</span>;
<span style="color: #228B22;">% Now brush some data points...</span>
uiinspect<span style="color: #080;">&#40;</span><span style="color: #0000FF;">gca</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 460px"><a
target="_blank" href="http://UndocumentedMatlab.com/images/Brushing2a.png"><img
alt="UIInspect-ion of a data-brushed plot" src="http://UndocumentedMatlab.com/images/Brushing2a.png" title="UIInspect-ion of a data-brushed plot" width="450" height="389" /></a><p
class="wp-caption-text">UIInspect-ion of a data-brushed plot (click for details)</p></div></center></p><p>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).</p><p>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).</p><p>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:</p><p><center><div
class="wp-caption aligncenter" style="width: 460px"><img
alt="UIInspect-ion of the data-brushing line" src="http://UndocumentedMatlab.com/images/Brushing2b.png" title="UIInspect-ion of the data-brushing line" width="450" height="325" /><p
class="wp-caption-text">UIInspect-ion of the data-brushing line</p></div></center></p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">hBrushLine = findall<span style="color: #080;">&#40;</span><span style="color: #0000FF;">gca</span>,<span style="color:#A020F0;">'tag'</span>,<span style="color:#A020F0;">'Brushing'</span><span style="color: #080;">&#41;</span>;
brushedData = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>hBrushLine, <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'Xdata'</span>,<span style="color:#A020F0;">'Ydata'</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
brushedIdx = ~<span style="color: #0000FF;">isnan</span><span style="color: #080;">&#40;</span>brushedData<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
brushedXData = brushedData<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#40;</span>brushedIdx<span style="color: #080;">&#41;</span>;
brushedYData = brushedData<span style="color: #080;">&#123;</span><span style="color: #33f;">2</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#40;</span>brushedIdx<span style="color: #080;">&#41;</span>;
<span style="color: #228B22;">% and similarly for ZData in 3D plots</span></pre></div></div><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.</p><p>As I have already explained in a <a
target="_blank" href="http://undocumentedmatlab.com/blog/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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; hNewVarMenuItem = findall<span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span>,<span style="color:#A020F0;">'tag'</span>,<span style="color:#A020F0;">'figDataManagerNewVar'</span><span style="color: #080;">&#41;</span>
hNewVarMenuItem =
          <span style="color: #33f;">742.000244140625</span>
&nbsp;
&gt;&gt; hNewVarCallback = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>hNewVarMenuItem,<span style="color:#A020F0;">'callback'</span><span style="color: #080;">&#41;</span>
hNewVarCallback = 
    @datamanager.<span style="">newvar</span>
&nbsp;
&gt;&gt; hNewVarCallback<span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span>   <span style="color: #228B22;">% activate the callback</span>
<span style="color: #228B22;">% =&gt; set 'ans' as the new variable holding the brushed data</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">ans</span>
<span style="color: #0000FF;">ans</span> =
                       <span style="color: #33f;">6.4</span>         <span style="color: #33f;">0.116549204850494</span>
                       <span style="color: #33f;">6.6</span>         <span style="color: #33f;">0.311541363513379</span>
                       <span style="color: #33f;">6.8</span>         <span style="color: #33f;">0.494113351138609</span>
                         <span style="color: #33f;">7</span>         <span style="color: #33f;">0.656986598718789</span>
                       <span style="color: #33f;">7.2</span>         <span style="color: #33f;">0.793667863849153</span>
                       <span style="color: #33f;">7.4</span>         <span style="color: #33f;">0.898708095811627</span>
                       <span style="color: #33f;">7.6</span>         <span style="color: #33f;">0.967919672031486</span>
                       <span style="color: #33f;">7.8</span>         <span style="color: #33f;">0.998543345374605</span>
                       <span style="color: #F0F;">...</span>         <span style="color: #F0F;">...</span></pre></div></div><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. <img
src='http://undocumentedmatlab.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /></p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/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='http://undocumentedmatlab.com/blog/accessing-the-matlab-editor/' rel='bookmark' title='Accessing the Matlab Editor'>Accessing the Matlab Editor</a> <small>The Matlab Editor can be accessed programmatically, for a wide variety of possible uses - this article shows how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/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><li><a
href='http://undocumentedmatlab.com/blog/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...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/accessing-plot-brushed-data/feed/</wfw:commentRss> <slash:comments>8</slash:comments> </item> </channel> </rss>

<!-- W3 Total Cache: Minify debug info:
Engine:             disk: basic
Theme:              b7666
Template:           tag
-->
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Served from: undocumentedmatlab.com @ 2012-05-21 19:41:12 -->

<!-- W3 Total Cache: Page cache debug info:
Engine:             disk: enhanced
Cache key:          blog/tag/callbacks/feed/_index.xml_gzip
Caching:            enabled
Status:             not cached
Creation Time:      2.164s
Header info:
X-Pingback:         http://undocumentedmatlab.com/blog/xmlrpc.php
Set-Cookie:         wpgb_visit_last_php-default=1337654470; expires=Wed, 22-May-2013 02:41:10 GMT; path=/
Content-Type:       text/xml; charset=UTF-8
Last-Modified:      Tue, 22 May 2012 02:41:12 GMT
Vary:               Accept-Encoding, Cookie
Expires:            Tue, 22 May 2012 03:41:12 GMT
Pragma:             public
Cache-Control:      public, must-revalidate, proxy-revalidate
Etag:               8b0e90fcef770b9292a98d47bc37f290
Content-Encoding:   gzip
-->
