<?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>Optical illusion &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/optical-illusion/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 04 May 2016 16:26:08 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
	<item>
		<title>Transparent labels</title>
		<link>https://undocumentedmatlab.com/articles/transparent-labels?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=transparent-labels</link>
					<comments>https://undocumentedmatlab.com/articles/transparent-labels#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 04 May 2016 16:26:08 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Optical illusion]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6403</guid>

					<description><![CDATA[<p>Matlab labels can be set to a transparent background as well as padding. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/transparent-labels">Transparent labels</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/transparent-legend" rel="bookmark" title="Transparent legend">Transparent legend </a> <small>Matlab chart legends are opaque be default but can be made semi- or fully transparent. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/toolbar-button-labels" rel="bookmark" title="Toolbar button labels">Toolbar button labels </a> <small>GUI toolbar button labels can easily be set and customized using underlying Java components. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-matlab-figure-window" rel="bookmark" title="Transparent Matlab figure window">Transparent Matlab figure window </a> <small>Matlab figure windows can be made fully or partially transparent/translucent or blurred - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/hyperlink-text-labels" rel="bookmark" title="Hyperlink text labels">Hyperlink text labels </a> <small>Hyperlink labels can easily be added to Matlab GUIs. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>For the application that I will be <a href="/articles/upcoming-public-matlab-presentations" target="_blank">presenting at next week&#8217;s MATLAB Expo</a> in Munich (<a href="/Pairformax/Expo-2016.pdf" target="_blank">presentation slides</a>), I wanted to add a text label at a specific location within the figure. The problem was, as you can clearly see from the screenshot below, that there is precious little available space for a new label. I could drive the entire content down to make space for it, but that would reduce the usable space for the actual contents, which is already at a premium:<br />
<center><a href="/images/Pairformax research2.png" target="_blank"><img decoding="async" alt="Adding a transparent label to Matlab GUI (click for full-size image)" src="https://undocumentedmatlab.com/images/Pairformax research2.png" title="Adding a transparent label to Matlab GUI (click for full-size image)" width="75%" style="max-width: 908px;" /></a><br />
Adding a transparent label to Matlab GUI (click for full-size image)</center><br />
A natural place for the new label, as indicated, would be on top of the empty space next to the content&#8217;s sub-tabs (Correlation and Backtesting). This empty space is taken up by Matlab&#8217;s <i><b>uitabgroup</b></i> control, and we can simply place our label on top of it.<br />
Well, easier said than done&#8230;<br />
<span id="more-6403"></span><br />
The obvious first attempt is to set the label&#8217;s position to <code>[0,0,1,1]</code> (in normalized units of its parent container). The label text will appear at the expected location, since Matlab labels are always top-aligned. However, the label&#8217;s opaque background will hide anything underneath (which is basically the entire content).<br />
If we set the label&#8217;s position to something smaller (say, <code>[.2,.9,.6,.1]</code>), the label will now hide a much smaller portion of the content, but will still mask part of it (depending of the exact size of the figure) and for very small figure might actually make the label too small to display. Making the label background transparent will solve this dilemma.<br />
Unfortunately, all Matlab controls are made opaque by default. Until recently there was not much that could be done about this, since all Matlab controls used heavyweight <code>java.awt.Panel</code>-derived containers that cannot be made transparent (<a href="/articles/javacomponent#comment-46580" target="_blank">details</a>). Fortunately, in HG2 (R2014b onward) <a href="/articles/customizing-matlab-uipanels" target="_blank">containers are now lightweight <code>javax.swing.JPanel</code>-derived</a> and we can transform them and their contained control from opaque to non-opaque (i.e., having a transparent background).<br />
There are 3 simple steps for this:</p>
<ol>
<li>Find the text label control&#8217;s underlying Java peer (control) reference handle. This can be done using my <a href="/articles/faster-findjobj" target="_blank"><i><b>findjobj</b></i> utility</a>, or by direct access via the containing <i><b>uipanel</b></i> hierarchy (if the label is inside such a <i><b>uipanel</b></i>), as explained <a href="/articles/customizing-matlab-uipanels" target="_blank">here</a>.</li>
<li>Set the Java label reference to be non-opaque (via its <a href="https://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#setOpaque(boolean)" target="_blank"><i>setOpaque()</i></a> method)</li>
<li>Repaint the label via its <i>repaint()</i> method</li>
</ol>
<pre lang="matlab">
% Create the Matlab text label uicontrol
hLabel = uicontrol('Style','text', 'Parent',hPanel, 'Units','norm', 'Pos',[0,0,1,1], 'String','Results for BERY / PKG (1 hour)');
% Get the underlying Java peer (control) reference
jLabel = findjobj(hLabel);
%jLabel = hPanel.JavaFrame.getGUIDEView.getComponent(0).getComponent(0).getComponent(0).getComponent(0);  % a direct alternative
% Set the control to be non-opaque and repaint it
jLabel.setOpaque(false);
jLabel.repaint();
</pre>
<p>This now looks nice, but not quite: Matlab displays the label text at the very top of its container, and this is not really in-line with the uitab labels. We need to add a small vertical padding at the top. One way to do this would be to set the label&#8217;s position to <code>[0,0,1,.99]</code> rather than <code>[0,0,1,1]</code>. Unfortunately, this results in varying amounts of padding depending on the container/figure height. A better alternative here would be to set the label to have a fixed-size padding amount. This can be done by attaching an empty <a href="https://docs.oracle.com/javase/7/docs/api/javax/swing/border/Border.html" rel="nofollow" target="_blank"><code>Border</code></a> to our <code>JLabel</code>:</p>
<pre lang="matlab">
% Attach a 6-pixel top padding
jBorder = javax.swing.BorderFactory.createEmptyBorder(6,0,0,0);  % top, left, bottom, right
jLabel.setBorder(jBorder);
</pre>
<p>Another limitation is that while the transparent background presents the illusion of emptiness, trying to interact with any of the contents beneath it using mouse clicks fails because the mouse clicks are trapped by the Label background, transparent though it may be. We could reduce the label&#8217;s size so that it occludes a smaller portion of the content. Alternatively, we can remove the label&#8217;s mouse listeners so that any mouse events are passed-through to the controls underneath (i.e., not consumed by the label control, or actually it&#8217;s internal Java container):</p>
<pre lang="matlab">
jLabelParent = jLabel.getParent;
% Remove the mouse listeners from the control's internal container
jListener = jLabelParent.getMouseListeners;
jLabelParent.removeMouseListener(jListener(1));
jListener = jLabelParent.getMouseMotionListeners;
jLabelParent.removeMouseMotionListener(jListener(1));
</pre>
<p>Using the label&#8217;s Java peer reference, we could do a lot of other neat stuff. A simple example for this is the <b>VerticalAlignment</b> or <b>LineWrap</b> properties &#8211; for some reason that eludes me, Matlab&#8217;s <i><b>uicontrol</b></i> only allows specifying the horizontal alignment and forces a line-wrap, despite the fact that these features are readily available in the underlying Java peer.<br />
Finally, while it is not generally a good design practice to change fonts throughout the GUI, it sometimes makes sense to use different font <font color="red">colors</font>, <font size=+3>sizes</font>, <code>faces</code> and/or <i><b>attributes</b></i> for parts of the label text, in various situations. For example, to <b>emphasize</b> certain things, as I&#8217;ve done in my title label. Such customizations can easily be done <a href="/articles/html-support-in-matlab-uicomponents" target="_blank">using HTML strings with most Matlab uicontrols</a>, but <a href="/articles/customizing-matlab-labels" target="_blank">unfortunately not for labels</a>, even today in R2016a. MathWorks created custom code that removes the HTML support in Matlab labels, for reasons that elude me yet again, especially since Matlab upcoming future GUI will probably be web-based so it will also natively support HTML, so maybe there&#8217;s still hope that HTML will be supported in Matlab labels in a future release.<br />
Anyway, the bottom line is that if we need our label to have HTML support today, we can use a standard Java <code>JLabel</code> and add it to the GUI using the <i><b>javacomponent</b></i> function. Here&#8217;s a simple usage example:</p>
<pre lang="matlab">
% Create the label and add it to the GUI
jLabel = javaObjectEDT(javax.swing.JLabel('<html>Results for <b>BERY / PKG (1 Hour)</b></html>'));
[hjLabel, hContainer] = javacomponent(jLabel, [10,10,10,10], hPanel);
set(hContainer, 'Units','norm', 'Pos',[0,0,1,1])
% Make the label (and its internal container) transparent
jLabel.getParent.getParent.setOpaque(false)  % label's internal container
jLabel.setOpaque(false)  % the label control itself
% Align the label
jLabel.setVerticalAlignment(jLabel.TOP);
jLabel.setHorizontalAlignment(jLabel.CENTER);
% Add 6-pixel top border padding and repaint the label
jLabel.setBorder(javax.swing.BorderFactory.createEmptyBorder(6,0,0,0));
jLabel.repaint;
% Now do the rest - mouse-listeners removal etc.
...
</pre>
<p>If you happen to attend the Matlab Expo next week in Munich Germany, please do come by and say hello!</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/transparent-labels">Transparent labels</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/transparent-legend" rel="bookmark" title="Transparent legend">Transparent legend </a> <small>Matlab chart legends are opaque be default but can be made semi- or fully transparent. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/toolbar-button-labels" rel="bookmark" title="Toolbar button labels">Toolbar button labels </a> <small>GUI toolbar button labels can easily be set and customized using underlying Java components. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-matlab-figure-window" rel="bookmark" title="Transparent Matlab figure window">Transparent Matlab figure window </a> <small>Matlab figure windows can be made fully or partially transparent/translucent or blurred - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/hyperlink-text-labels" rel="bookmark" title="Hyperlink text labels">Hyperlink text labels </a> <small>Hyperlink labels can easily be added to Matlab GUIs. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/transparent-labels/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Hyperlink text labels</title>
		<link>https://undocumentedmatlab.com/articles/hyperlink-text-labels?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=hyperlink-text-labels</link>
					<comments>https://undocumentedmatlab.com/articles/hyperlink-text-labels#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 21 Oct 2015 14:42:48 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Optical illusion]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6033</guid>

					<description><![CDATA[<p>Hyperlink labels can easily be added to Matlab GUIs. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/hyperlink-text-labels">Hyperlink text labels</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/transparent-labels" rel="bookmark" title="Transparent labels">Transparent labels </a> <small>Matlab labels can be set to a transparent background as well as padding. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-matlab-labels" rel="bookmark" title="Customizing Matlab labels">Customizing Matlab labels </a> <small>Matlab's text uicontrol is not very customizable, and does not support HTML or Tex formatting. This article shows how to display HTML labels in Matlab and some undocumented customizations...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/toolbar-button-labels" rel="bookmark" title="Toolbar button labels">Toolbar button labels </a> <small>GUI toolbar button labels can easily be set and customized using underlying Java components. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>It is often useful to include hyperlinked text labels in GUIs. Such labels provide single-click access to important functionality, improve branding, and are non-intrusive action controls having a lower visual impact than a full-blown button. There are several ways that we can display such hyperlinks in Matlab GUIs, and today I will show one of my favorites.<br />
The basic idea is to create a Java text label control whose label displays an HTML link. The control is modified to change the mouse cursor when it hovers over the hyperlink, and a mouse-click callback is set to open the hyperlink target in the system browser:<br />
<figure style="width: 150px" class="wp-caption alignright"><img decoding="async" src="https://undocumentedmatlab.com/blog/wp-content/uploads/2009/04/button_link-150x150.png" alt="hyperlink text label" title="hyperlink text label" width="150" height="150" class="size-thumbnail wp-image-198" /><figcaption class="wp-caption-text">hyperlink text label</figcaption></figure></p>
<pre lang='matlab'>
% Create and display the text label
url = 'UndocumentedMatlab.com';
labelStr = ['<html>More info: <a href="">' url '</a></html>'];
jLabel = javaObjectEDT('javax.swing.JLabel', labelStr);
[hjLabel,hContainer] = javacomponent(jLabel, [10,10,250,20], gcf);
% Modify the mouse cursor when hovering on the label
hjLabel.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.HAND_CURSOR));
% Set the label's tooltip
hjLabel.setToolTipText(['Visit the ' url ' website']);
% Set the mouse-click callback
set(hjLabel, 'MouseClickedCallback', @(h,e)web(['http://' url], '-browser'))
</pre>
<p><span id="more-6033"></span><br />
Note the visual illusion here: we do not directly click the hyperlink (note that its <code>href</code> is empty), but rather the label control. The end-result is the same.<br />
Also note that this technique could be used to easily display clickable icons/images, including animated and transparent GIFs, by simply setting the label&#8217;s HTML string to display the relevant image. I have already shown how to do this in <a target="_blank" href="/articles/displaying-animated-gifs">another post</a>. Uses could range from clickable logo images to clickable help icons.<br />
We could also use a flat (borderless) button. I have already posted related articles about button customizations in Matlab GUIs (<a target="_blank" href="/articles/button-customization">here</a>, <a target="_blank" href="/articles/customizing-matlab-labels">here</a> and <a target="_blank" href="/articles/borderless-button-used-for-plot-properties">here</a>). In fact, I have already shown how we can use <a target="_blank" href="/articles/borderless-button-used-for-plot-properties">borderless buttons in Matlab axes</a> to display a non-obtrusive control for controlling plot properties. The code would be very similar to the above, except that we would use a <code>JButton</code> rather than a <code>JLabel</code>, and also need to <i>setBorder([])</i> and similar button-specific modifications. Buttons have a bit more functionality and customizability than simple text labels; the appearance would be the same, but the extra customizability may be handy in very special cases, although not for most use-cases.<br />
One of the benefits of using either <code>JLabels</code> or <code>JButtons</code> is that they enable <a target="_blank" href="/articles/uicontrol-callbacks">multiple callbacks</a> (e.g., <code>FocusGained,FocusLost</code>) and properties (e.g., <code>VerticalAlignment,ToolTipText</code>) that the standard Matlab text uicontrol does not provide (not to mention their builtin ability to display HTML, which Matlab&#8217;s uicontrol text labels do not posses).</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/hyperlink-text-labels">Hyperlink text labels</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/transparent-labels" rel="bookmark" title="Transparent labels">Transparent labels </a> <small>Matlab labels can be set to a transparent background as well as padding. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-matlab-labels" rel="bookmark" title="Customizing Matlab labels">Customizing Matlab labels </a> <small>Matlab's text uicontrol is not very customizable, and does not support HTML or Tex formatting. This article shows how to display HTML labels in Matlab and some undocumented customizations...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/toolbar-button-labels" rel="bookmark" title="Toolbar button labels">Toolbar button labels </a> <small>GUI toolbar button labels can easily be set and customized using underlying Java components. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/hyperlink-text-labels/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Auto-completion widget</title>
		<link>https://undocumentedmatlab.com/articles/auto-completion-widget?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=auto-completion-widget</link>
					<comments>https://undocumentedmatlab.com/articles/auto-completion-widget#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 29 Apr 2015 21:07:24 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Optical illusion]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5763</guid>

					<description><![CDATA[<p>Matlab includes a variety of undocumented internal controls that can be used for an auto-completion component. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/auto-completion-widget">Auto-completion widget</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/builtin-popuppanel-widget" rel="bookmark" title="Builtin PopupPanel widget">Builtin PopupPanel widget </a> <small>We can use a built-in Matlab popup-panel widget control to display lightweight popups that are attached to a figure window. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/auto-scale-image-colors" rel="bookmark" title="Auto-scale image colors">Auto-scale image colors </a> <small>Images can be automatically color-scaled for maximum resolution, using the undocumented MarkedClean event. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/class-object-tab-completion-and-improper-field-names" rel="bookmark" title="Class object tab completion &amp; improper field names">Class object tab completion &amp; improper field names </a> <small>Tab completions and property access can be customized for user-created Matlab classes. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-2" rel="bookmark" title="Programmatic shortcuts manipulation &#8211; part 2">Programmatic shortcuts manipulation &#8211; part 2 </a> <small>Non-standard shortcut controls and customizations can easily be added to the Matlab desktop. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Do you ever get a feeling when designing a Matlab GUI, that existing components/controls are simply not enough to achieve the desired functionality/appearance?<br />
Such a case happened to me, when a consulting client asked me to integrate an auto-completion widget in a GUI that I designed for them. The idea was simple enough: the user selects a class of financial assets from a drop-down, then one or more actual financial securities from a dynamically-populated drop-down (based on the asset class), then the date range and analysis function, and finally the results are plotted in the main panel. The idea was for Matlab to automatically auto-complete the financial instruments matching the entered text, as it is being typed, similarly to other standard auto-completion widgets (e.g., Google&#8217;s search box), including the use of wildcards and regular expressions:<br />
<center><figure style="width: 370px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" alt="Interactive Matlab auto-completion widget" src="https://undocumentedmatlab.com/images/AssetSearch_small_animated.gif" title="Interactive Matlab auto-completion widget" width="370" height="185" /><figcaption class="wp-caption-text">Interactive Matlab auto-completion widget</figcaption></figure></center><br />
Note that in this particular case, I use the term &#8220;auto-completion&#8221; loosely. The correct term should actually be &#8220;auto-winnowing&#8221; or &#8220;auto-filtering&#8221;. <i>Auto-completion</i> is usually reserved for the case of the user-entered text being automatically completed as they type, whereas <i>auto-winnowing</i> only updates the drop-down options on-the-fly. These two functionalities are often correlated, and today&#8217;s article will discuss both.<br />
<span id="more-5763"></span></p>
<h3 id="AutoCompletionList">AutoCompletionList</h3>
<p>Before I dive into details of the implementation I ended up with, note that there are simpler alternatives. For example, we can use Matlab&#8217;s internal <code>com.mathworks.widgets.AutoCompletionList</code> widget:</p>
<pre lang='matlab'>
strs = {'This','is','test1','test2'};
strList = java.util.ArrayList;
for idx = 1 : length(strs),  strList.add(strs{idx});  end
jPanelObj = com.mathworks.widgets.AutoCompletionList(strList,'');
javacomponent(jPanelObj.getComponent, [10,10,200,100], gcf);
</pre>
<p><center><figure style="width: 200px" class="wp-caption aligncenter"><img decoding="async" alt="AutoCompletionList widget" src="https://undocumentedmatlab.com/images/AutoCompletionList.png" title="AutoCompletionList widget" width="200" height="100" /><figcaption class="wp-caption-text">AutoCompletionList widget</figcaption></figure></center><br />
The <code>AutoCompletionList</code> control is actually a list (rather than a drop-down), where the user types an entry in the header row. The control automatically selects the first corresponding list item and auto-completes the rest of the entry. Invalid user entries generate a beep and are not allowed by default (unless the widget&#8217;s <b>Strict</b> property is cleared: <code>jPanelObj.setStrict(false)</code>). The visible list size can be controlled by setting the widget&#8217;s <b>VisibleRowCount</b> property (<code>jPanelObj.setVisibleRowCount(6)</code>).<br />
Items can be selected by either typing in the header row, by selecting a list item, or programmatically (<code>jPanelObj.setSelectedValue('test1')</code>). The currently selected item is retrieved via the same <b>SelectedValue</b> property (<code>selectedValue = char(jPanelObj.getSelectedValue)</code>). As with many other actionable Java controls, we can attach a callback on the <b>ActionPerformed</b> event:</p>
<pre lang='matlab'>set(handle(jPanelObj,'callbackproperties'), 'ActionPerformedCallback', @myMatlabCallbackFunc);</pre>
<p>We can attach a similar callback to key-typing within the header row (text field), by accessing the widget&#8217;s internal component (which is the one that is actually being displayed via the <i><b><a target="_blank" href="/articles/javacomponent">javacomponent</a></b></i> function):</p>
<pre lang='matlab'>set(handle(jPanelObj.getComponent,'callbackproperties'), 'KeyTypedCallback', @myMatlabCallbackFunc);</pre>
<h3 id="SearchTextField">SearchTextField</h3>
<p>For my client&#8217;s purposes, however, <code>AutoCompletionList</code> could not be used. We wanted a drop-down selector that takes up far less space than a listbox. The first thought was to use a modified drop-down (<a target="_blank" href="/articles/editable-combo-box">editable combo-box</a>). This turned out to be less effective than hoped, because of the interference between the Matlab <b>KeyTypedCallback</b> function and the automatic behavior of the combo-box. I do not rule out the use of such an editable combo-box in other use-cases, but for this implementation I chose to use a different control, namely Matlab&#8217;s internal <code>com.mathworks.widgets.SearchTextField</code>, which has some nice additional features such as an optional light-gray prompt, and a clickable search icon that changes its appearance and behavior based on the entered text:</p>
<pre lang='matlab'>
jPanelObj = com.mathworks.widgets.SearchTextField('Enter search term:');
[jhPanel,hContainer] = javacomponent(jPanelObj.getComponent, [10,10,150,25], gcf);
</pre>
<table style="border: 0; background: none;">
<tr>
<td style="border: 0; vertical-align: top;"><center><figure style="width: 150px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="SearchTextField initial view" src="https://undocumentedmatlab.com/images/SearchTextField1.png" title="SearchTextField initial view" width="150" height="25" /><figcaption class="wp-caption-text">SearchTextField initial view</figcaption></figure></center></td>
<td style="border: 0; vertical-align: top;"><center><figure style="width: 150px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="user clicks in entry box (prompt text disappears)" src="https://undocumentedmatlab.com/images/SearchTextField2.png" title="user clicks in entry box (prompt text disappears)" width="150" height="25" /><figcaption class="wp-caption-text">user clicks in entry box (prompt text disappears)</figcaption></figure></center></td>
<td style="border: 0; vertical-align: top;"><center><figure style="width: 150px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="user types something (icon changes to 'x', clicking it will clear the text)" src="https://undocumentedmatlab.com/images/SearchTextField3.png" title="user types something (icon changes to 'x', clicking it will clear the text)" width="150" height="25" /><figcaption class="wp-caption-text">user types something<br />(icon changes to 'x', clicking it will clear the text)</figcaption></figure></center></td>
</tr>
</table>
<h3 id="Illusion">An optical illusion</h3>
<p>As with a regular combo-box, the dropdown-menu integration in Matlab proved a bit difficult, especially due to the auto-completion feature. Again, I do not rule out using it in other use-cases, but for this implementation I chose to use a visual illusion: an actual combo-box is placed beneath (hidden by) the <code>SearchTextField</code> control. So basically, we are seeing two separate parts of two different components: the edit-box of the <code>SearchTextField</code>, and the dropdown panel (a <code>JPopupMenu</code>) of the hidden combo-box. They appear attached, providing the optical illusion of being a single widget, when in fact they are not. Neat, right?</p>
<pre lang="matlab">
function createMainGUI()
   ...
   handles.cbAssetSearch = createAssetSelector(hAssetSearchPanel);
   ...
end
% Create the asset-name selector control within a parent container (panel/figure/tab/...)
function hContainer = createAssetSelector(hParent)
    % Create a uipanel to hold both sub-components below, one occluding the other:
    hContainer = handle(uipanel('BorderType','none', 'Parent',hParent));
    % Create a standard editable combo-box (drop-down) control
    callback = {@searchComboUpdated,hContainer};  % set to [] to disable asset combo selection callback
    hContainer1 = createComboSelector(hContainer, {'All'}, callback, true);
    set(hContainer1, 'Units','pixels', 'Position',[1,1,2,2]);
    % Create a SearchTextField control on top of the combo-box
    jAssetChooser = com.mathworks.widgets.SearchTextField('Enter search:');
    jAssetComponent = jAssetChooser.getComponent;
    [jhAssetComponent, hContainer2] = javacomponent(jAssetComponent,[],hContainer);
    hContainer2 = handle(hContainer2);
    set(hContainer2, 'tag','hAssetContainer', 'UserData',jAssetChooser, 'Units','norm', 'Position',[0,0,1,1]);
    setappdata(hContainer,'jAssetChooser',jAssetChooser);
    % Expand the SearchTextField component to max available width
    jSize = java.awt.Dimension(9999, 20);
    jAssetComponent.getComponent(0).setMaximumSize(jSize);
    jAssetComponent.getComponent(0).setPreferredSize(jSize);
    % Add callback handlers
    hjSearchButton = handle(jAssetComponent.getComponent(1), 'CallbackProperties');
    set(hjSearchButton, 'MouseClickedCallback', {@updateSearch,jCombo,jAssetChooser});
    hjSearchField = handle(jAssetComponent.getComponent(0), 'CallbackProperties');
    set(hjSearchField, 'KeyPressedCallback', {@updateSearch,jCombo,jAssetChooser});
    jCombo = handle(hContainer1.UserData, 'CallbackProperties');
    jComboField = handle(jCombo.getComponent(2), 'CallbackProperties');
    set(jComboField, 'KeyPressedCallback', {@updateSearch,jCombo,[]});
    set(jCombo, 'FocusLostCallback', @(h,e)jCombo.hidePopup);  % hide the popup when another component is selected
    % Return the containing panel handle
    hContainer.UserData = [jCombo, jhAssetComponent, handle(jAssetChooser)];
end  % createAssetSelector
function hContainer = createComboSelector(hParent, strings, callback, isEditable)
   % Note: MJComboBox is better than JComboBox: the popup panel has more width than the base control if needed
   jComboBox = com.mathworks.mwswing.MJComboBox(strings);  % =javax.swing.JComboBox(strings);
   jComboBox.setEditable(isEditable);
   jComboBox.setBackground(java.awt.Color.white); % unfortunately, this only affects editable combos
   [jhComboBox, hContainer] = javacomponent(jComboBox, [], hParent);
   set(jhComboBox, 'ActionPerformedCallback', callback);
   hContainer = handle(hContainer);
   set(hContainer, 'tag','hAssetContainer', 'UserData',jComboBox);
end
</pre>
<p>where the callback function for item selection might look something like this (here&#8217;s an example of the callback for the asset-search selector):</p>
<pre lang="matlab">
% Callback function for the asset selector combo
function searchComboUpdated(jCombo, eventData, hPanel)
    selectedItem = regexprep(char(jCombo.getSelectedItem),'<[^>]*>','');  % strip away HTML tags
    jSearchTextField = hPanel.UserData(2).getComponent(0);
    jSearchTextField.setText(selectedItem);
    jSearchTextField.repaint; drawnow; pause(0.01);
    jAssetChooser = getappdata(hPanel,'jAssetChooser');
    updateSearch([],[],jCombo,jAssetChooser);
end  % searchComboUpdated
</pre>
<p>Callback events are used to synchronize the components, update the combo-box&#8217;s dropdown options and display the dropdown panel. We attach the same callback function, <code>updateSearch()</code>, to 3 separate events: <b>MouseClickedCallback</b> on the <code>SearchTextField</code>&#8216;s search button (icon), <b>KeyPressedCallback</b> on the search text-box, and another <b>KeyPressedCallback</b> on the combo-box&#8217;s text-box (which is not visible, but automatically receives focus when the user interacts with the popup menu (drop-down panel):</p>
<pre lang='matlab'>
% Create the SearchTextField component (after the hidden combo was created)
jAssetChooser = com.mathworks.widgets.SearchTextField('Enter search:');
jAssetComponent = jAssetChooser.getComponent;
[jhAssetComponent, hContainer] = javacomponent(jAssetComponent,[],hPanel);
% Set callbacks:
% 1) search icon mouse-click
hjSearchButton = handle(jAssetComponent.getComponent(1), 'CallbackProperties');
set(hjSearchButton, 'MouseClickedCallback', {@updateSearch,jCombo,jAssetChooser});
% 2) search textbox key-click
hjSearchField = handle(jAssetComponent.getComponent(0), 'CallbackProperties');
set(hjSearchField, 'KeyPressedCallback', {@updateSearch,jCombo,jAssetChooser});
% 3) popup panel key-click
jComboField = handle(jCombo.getComponent(2), 'CallbackProperties');
set(jComboField, 'KeyPressedCallback', {@updateSearch,jCombo,[]});
</pre>
<p>(note that these callbacks were included in the <code>createAssetSelector()</code> example above)<br />
The user can now select an item either from the combo-box&#8217;s dropdown panel, or by typing in the search text-box. Here is the implementation of the <code>updateSearch()</code> callback function:</p>
<pre lang='matlab'>
% Asset search popup combo button click callback
function updateSearch(hObject, eventData, jCombo, jAssetChooser) %#ok<inusl>
    persistent lastSearchText
    if isempty(lastSearchText),  lastSearchText = '';  end
    try
        % event occurred on the search field component
        try
            searchText = jAssetChooser.getSearchText;
            jSearchTextField = jAssetChooser.getComponent.getComponent(0);
        catch
            % Came via asset change - always update
            jSearchTextField = jAssetChooser.getComponent(0);
            searchText = jSearchTextField.getText;
            lastSearchText = '!@#$';
        end
    catch
        try
            % event occurred on the jCombo-box itself
            searchText = jCombo.getSelectedItem;
        catch
            % event occurred on the internal edit-field sub-component
            searchText = jCombo.getText;
            jCombo = jCombo.getParent;
        end
        jSearchTextField = jCombo.getComponent(jCombo.getComponentCount-1);
    end
    searchText = strrep(char(searchText), '*', '.*');  % turn into a valid regexp
    searchText = regexprep(searchText, '<[^>]+>', '');
    if strcmpi(searchText, lastSearchText) && ~isempty(searchText)
        jCombo.showPopup;
        return;  % maybe just clicked an arrow key or Home/End - no need to refresh the popup panel
    end
    lastSearchText = searchText;
    assetClassIdx = getappdata(handles.cbAssetClass, 'assetClassIdx');
    if isempty(assetClassIdx)
        jCombo.hidePopup;
        return;
    elseif isempty(searchText)
        assetNamesIdx = assetClassIdx;
    else
        searchComponents = strsplit(searchText, ' - ');
        assetCodeIdx = ~cellfun('isempty',regexpi(data.header.AssetCode(assetClassIdx),searchComponents{1}));
        assetNameIdx = ~cellfun('isempty',regexpi(data.header.AssetName(assetClassIdx),searchComponents{end}));
        if numel(searchComponents) > 1
            assetNamesIdx = assetClassIdx(assetCodeIdx & assetNameIdx);
        else
            assetNamesIdx = assetClassIdx(assetCodeIdx | assetNameIdx);
        end
    end
    setappdata(handles.cbAssetSearch, 'assetNameIdx', assetNamesIdx);
    if isempty(assetNamesIdx)
        jCombo.hidePopup;
        jSearchTextField.setBackground(java.awt.Color.yellow);
        jSearchTextField.setForeground(java.awt.Color.red);
        newFont = jSearchTextField.getFont.deriveFont(uint8(java.awt.Font.BOLD));
        jSearchTextField.setFont(newFont);
        return;
    else
        jSearchTextField.setBackground(java.awt.Color.white);
        jSearchTextField.setForeground(java.awt.Color.black);
        newFont = jSearchTextField.getFont.deriveFont(uint8(java.awt.Font.PLAIN));
        jSearchTextField.setFont(newFont);
    end
    % Compute the filtered asset names (highlight the selected search term)
    assetNames = strcat(data.header.AssetCode(assetNamesIdx), ' -=', data.header.AssetName(assetNamesIdx));
    assetNames = regexprep(assetNames, '(.+) -=\1', '$1', 'ignorecase');
    assetNames = unique(strrep(assetNames, ' -=', ' - '));
    if ~isempty(searchText)
        assetNames = regexprep(assetNames, ['(' searchText ')'], '<b><font color=blue>$1</font></b>', 'ignorecase');
        assetNames = strcat('<html>', assetNames);
    end
    % Redisplay the updated combo-box popup panel
    jCombo.setModel(javax.swing.DefaultComboBoxModel(assetNames));
    jCombo.showPopup;
end  % updateSearch
</pre>
<p>Here is what the final result looks like and behaves:<br />
<center><figure style="width: 500px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Matlab GUI with integrated auto-completion &#038; date selection widgets" src="https://undocumentedmatlab.com/images/AssetSearch_500x386b_animated.gif" title="Matlab GUI with integrated auto-completion &#038; date selection widgets" width="500" height="386" /><figcaption class="wp-caption-text">Matlab GUI with integrated auto-completion & date selection widgets</figcaption></figure></center><br />
Would you believe that this entire program is only 400 lines of code?!</p>
<h3 id="Conclusion">Conclusion</h3>
<p>I&#8217;ve heard it say on occasion that Matlab GUI is not really suited for professional applications. I completely disagree, and hope that today&#8217;s article proves otherwise. You can make Matlab GUI do wonders, in various different ways. Matlab does have limitations, but they are nowhere close to what many people believe. If you complain that your GUI sucks, then it is likely not because of Matlab&#8217;s lack of abilities, but because you are only using a very limited portion of them. This is no different than any other programming environment (admittedly, such features are much better documented in other environments).<br />
In short, to improve your GUI&#8217;s functionality and appearance, you just need to spend a bit of time searching for the right components (possibly using <a target="_blank" href="/books/matlab-java">my book</a>), or hire a professional consultant to do it for you. But of course, just bitching about Matlab&#8217;s supposed limitations is much easier&#8230;<br />
Do you have a GUI that you find hard to believe can be done (or improved) in Matlab? Contact me for a consulting proposal and let me surprise you!</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/auto-completion-widget">Auto-completion widget</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/builtin-popuppanel-widget" rel="bookmark" title="Builtin PopupPanel widget">Builtin PopupPanel widget </a> <small>We can use a built-in Matlab popup-panel widget control to display lightweight popups that are attached to a figure window. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/auto-scale-image-colors" rel="bookmark" title="Auto-scale image colors">Auto-scale image colors </a> <small>Images can be automatically color-scaled for maximum resolution, using the undocumented MarkedClean event. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/class-object-tab-completion-and-improper-field-names" rel="bookmark" title="Class object tab completion &amp; improper field names">Class object tab completion &amp; improper field names </a> <small>Tab completions and property access can be customized for user-created Matlab classes. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-2" rel="bookmark" title="Programmatic shortcuts manipulation &#8211; part 2">Programmatic shortcuts manipulation &#8211; part 2 </a> <small>Non-standard shortcut controls and customizations can easily be added to the Matlab desktop. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/auto-completion-widget/feed</wfw:commentRss>
			<slash:comments>23</slash:comments>
		
		
			</item>
		<item>
		<title>Plot legend title</title>
		<link>https://undocumentedmatlab.com/articles/plot-legend-title?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=plot-legend-title</link>
					<comments>https://undocumentedmatlab.com/articles/plot-legend-title#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 01 Apr 2015 19:21:26 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Optical illusion]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5674</guid>

					<description><![CDATA[<p>Titles to plot legends are easy to achieve in HG1 (R2014a or earlier), but much more difficult in HG2 (R2014b or newer). </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/plot-legend-title">Plot legend title</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/plot-legend-customization" rel="bookmark" title="Plot legend customization">Plot legend customization </a> <small>Matlab plot legends and their internal components can be customized using a variety of undocumented properties that are easily accessible. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/bug-and-workaround-in-timeseries-plot" rel="bookmark" title="Bug and workaround in timeseries plot">Bug and workaround in timeseries plot </a> <small>Matlab's internal hgconvertunits function has a bug that affects timeseries plots. Luckily there is a simple workaround....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-legend" rel="bookmark" title="Transparent legend">Transparent legend </a> <small>Matlab chart legends are opaque be default but can be made semi- or fully transparent. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/multi-column-grid-legend" rel="bookmark" title="Multi-column (grid) legend">Multi-column (grid) legend </a> <small>This article explains how to use undocumented axes listeners for implementing multi-column plot legends...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>This blog post was supposed to be a piece of cake: The problem description was that we wish to display a text title next to the legend box in plot axes. Sounds simple enough. After all, in HG1 (R2014a and earlier), a legend was a simple wrapper around a standard Matlab axes. Therefore, we can simply access the legend axes&#8217;s title handle, and modify its properties. This works very well in HG1:</p>
<pre lang='matlab'>
hold all;
hLine1 = plot(1:5);
hLine2 = plot(2:6);
hLegend = legend([hLine1,hLine2], 'Location','NorthWest');
hTitle = get(hLegend,'title');
set(hTitle, 'String','Plot types:', 'VerticalAlignment','middle', 'FontSize',8);
</pre>
<p><center><figure style="width: 220px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Matlab HG1 legend with title" src="https://undocumentedmatlab.com/images/HG1_legend_title.gif" title="Matlab HG1 legend with title" width="220" height="170" /><figcaption class="wp-caption-text">Matlab HG1 legend with title</figcaption></figure></center></p>
<h3 id="HG2">HG2</h3>
<p>How hard then could a corresponding solution be in HG2 (R2014b+), right?<br />
Well, it turns out that hard enough (at least for me)&#8230;<br />
<span id="more-5674"></span><br />
In this blog I&#8217;ve presented ~300 posts so far that discuss solutions to problems. Readers of this blog always hear the success stories, and might mistakenly think that every problem has a similarly simple solution that can be hacked away in a few lines of nifty code.<br />
Well, the truth must be told that for each investigation that yields such a success story, there is at least one other investigation in which I failed to find a solution, no matter how hard I tried or countless hours spent digging (this is not to say that the success stories are easy &#8211; distilling a solution to a few lines of code often takes hours of research). In any case, maybe some of these problems for which I have not found a solution do have one that I have simply not discovered, and maybe they don&#8217;t &#8211; in most likelihood I will never know.<br />
This is yet another example of such a spectacular failure on my part. Try as I may in HG2, I could find no internal handle anywhere to the legend&#8217;s axes or title handle. As far as I could tell, HG2&#8217;s legend is a standalone object of class <code>matlab.graphics.illustration.Legend</code> that derives from exactly the same <i><b>superclasses</b></i> as axes:</p>
<table>
<tbody>
<tr>
<td>
<pre lang='matlab'>
>> sort(superclasses('matlab.graphics.axis.Axes'))
ans =
    'JavaVisible'
    'dynamicprops'
    'handle'
    'matlab.graphics.Graphics'
    'matlab.graphics.GraphicsDisplay'
    'matlab.graphics.internal.GraphicsJavaVisible'
    'matlab.mixin.CustomDisplay'
    'matlab.mixin.Heterogeneous'
    'matlab.mixin.SetGet'
</pre>
</td>
<td>
<pre lang='matlab'>
>> sort(superclasses('matlab.graphics.illustration.Legend'))
ans =
    'JavaVisible'
    'dynamicprops'
    'handle'
    'matlab.graphics.Graphics'
    'matlab.graphics.GraphicsDisplay'
    'matlab.graphics.internal.GraphicsJavaVisible'
    'matlab.mixin.CustomDisplay'
    'matlab.mixin.Heterogeneous'
    'matlab.mixin.SetGet'
</pre>
</td>
</tr>
</tbody>
</table>
<p>This make sense, since they share many properties/features. But it also means that legends are apparently <i>not</i> axes but rather unrelated siblings. As such, if MathWorks chose to remove the Title property from the legend object, we will never find it.</p>
<h3 id="workaround">So what <i>can</i> we do in HG2?</h3>
<p>Well, we can always resort to the poor-man&#8217;s solution of an <a target="_blank" href="/articles/tag/optical-illusion">optical illusion</a>: displaying a an invisible axes object having the same Position as the legend box, with an axes title. We attach property listeners on the legend&#8217;s Units, Position and Visible properties, linking them to the corresponding axes properties, so that the title will change if and when the legend&#8217;s properties change (for example, by dragging the legend to a different location, or by resizing the figure). We also add an event listener to destroy the axes (and its title) when the legend is destroyed:</p>
<pre lang='matlab'>
% Create the legend
hLegend = legend(...);  % as before
% Create an invisible axes at the same position as the legend
hLegendAxes = axes('Parent',hLegend.Parent, 'Units',hLegend.Units, 'Position',hLegend.Position, ...
                   'XTick',[] ,'YTick',[], 'Color','none', 'YColor','none', 'XColor','none', 'HandleVisibility','off', 'HitTest','off');
% Add the axes title (will appear directly above the legend box)
hTitle = title(hLegendAxes, 'Plot types:', 'FontWeight','normal', 'FontSize',8);  % Default is bold-11, which is too large
% Link between some property values of the legend and the new axes
hLinks = linkprop([hLegend,hLegendAxes], {'Units', 'Position', 'Visible'});
% persist hLinks, otherwise they will stop working when they go out of scope
setappdata(hLegendAxes, 'listeners', hLinks);
% Add destruction event listener (no need to persist here - this is done by addlistener)
addlistener(hLegend, 'ObjectBeingDestroyed', @(h,e)delete(hLegendAxes));
</pre>
<p><center><figure style="width: 220px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Matlab HG2 legend with title" src="https://undocumentedmatlab.com/images/HG2_legend_title.gif" title="Matlab HG2 legend with title" width="220" height="180" /><figcaption class="wp-caption-text">Matlab HG2 legend with title</figcaption></figure></center><br />
Yes, this is indeed a bit of an unfortunate regression from HG1, but I currently see no other way to solve this. We can&#8217;t win &#8217;em all&#8230; If you know a better solution, I&#8217;m all ears. Please shoot me an email, or leave a comment below.<br />
<b><u>Update:</u></b> As suggested below by Martin, here is a more elegant solution, which attaches a <i><b>text</b></i> object as a direct child of the legend&#8217;s hidden property DecorationContainer (we cannot add it as a child of the legend since this is prevented and results in an error):</p>
<pre lang='matlab'>
hLegend = legend(...);
hlt = text(...
    'Parent', hLegend.DecorationContainer, ...
    'String', 'Title', ...
    'HorizontalAlignment', 'center', ...
    'VerticalAlignment', 'bottom', ...
    'Position', [0.5, 1.05, 0], ...
    'Units', 'normalized');
</pre>
<p>The title appears to stay attached to the legend and the Parent property of the text object even reports the legend object as its parent:</p>
<pre lang='matlab'>
hLegend.Location = 'southwest';  % Test the title's attachment
hlt.Parent % Returns hLegend
</pre>
<p>&#8211; thanks Martin!<br />
Happy Passover/Easter everybody!<br />
<b><u>Addendum</u></b>: As pointed out by Eike in <a href="#comment-408067" rel="nofollow">a comment below</a>, Matlab release R2016a has restored the <b>Title</b> property. This property holds a handle to a <code>Text</code> object, for which we can set properties such as <b>String</b>, <b>Color</b>, <b>FontSize</b> etc.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/plot-legend-title">Plot legend title</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/plot-legend-customization" rel="bookmark" title="Plot legend customization">Plot legend customization </a> <small>Matlab plot legends and their internal components can be customized using a variety of undocumented properties that are easily accessible. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/bug-and-workaround-in-timeseries-plot" rel="bookmark" title="Bug and workaround in timeseries plot">Bug and workaround in timeseries plot </a> <small>Matlab's internal hgconvertunits function has a bug that affects timeseries plots. Luckily there is a simple workaround....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-legend" rel="bookmark" title="Transparent legend">Transparent legend </a> <small>Matlab chart legends are opaque be default but can be made semi- or fully transparent. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/multi-column-grid-legend" rel="bookmark" title="Multi-column (grid) legend">Multi-column (grid) legend </a> <small>This article explains how to use undocumented axes listeners for implementing multi-column plot legends...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/plot-legend-title/feed</wfw:commentRss>
			<slash:comments>11</slash:comments>
		
		
			</item>
		<item>
		<title>Frameless (undecorated) figure windows</title>
		<link>https://undocumentedmatlab.com/articles/frameless-undecorated-figure-windows?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=frameless-undecorated-figure-windows</link>
					<comments>https://undocumentedmatlab.com/articles/frameless-undecorated-figure-windows#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 19 Mar 2015 22:00:37 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[JavaFrame]]></category>
		<category><![CDATA[Optical illusion]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5642</guid>

					<description><![CDATA[<p>Matlab figure windows can be made undecorated (borderless, title-less). </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/frameless-undecorated-figure-windows">Frameless (undecorated) figure windows</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/figure-window-customizations" rel="bookmark" title="Figure window customizations">Figure window customizations </a> <small>Matlab figure windows can be customized in numerous manners using the underlying Java Frame reference. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/blurred-matlab-figure-window" rel="bookmark" title="Blurred Matlab figure window">Blurred Matlab figure window </a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/minimize-maximize-figure-window" rel="bookmark" title="Minimize/maximize figure window">Minimize/maximize figure window </a> <small>Matlab figure windows can easily be maximized, minimized and restored using a bit of undocumented magic powder...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>All Matlab figures have a standard frame around them, consisting of a border and title bar. In some cases it could be useful to present a figure window, displaying only the contents without the border and title bar. Such a borderless (undecorated) window is not possible in Matlab. Well, at least not in supported/documented Matlab&#8230;<br />
Readers of this blog and/or my <a target="_blank" href="/books/matlab-java">Matlab-Java programming book</a> are aware that Matlab&#8217;s GUI is based on Java Swing. In the end, every Matlab figure window is a simple Java <code><a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html">JFrame</a></code>, and JFrames have a <i>setUndecorated(true)</i> method that can be called to remove the border and title bar.<br />
<center><img decoding="async" alt="An undecorated Matlab figure window" src="https://undocumentedmatlab.com/images/undecorated_figure.gif" title="An undecorated Matlab figure window" width="80%" style="max-width: 616px;" /><br />An undecorated Matlab figure window</center><br />
<span id="more-5642"></span></p>
<h3 id="1">Attempt #1 &#8211; direct invocation</h3>
<p>Unfortunately, we cannot directly call <i>setUndecorated</i> in Matlab, because it only works when the <code>JFrame</code> has not yet been displayed:</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Get the figure's underlying Java JFrame reference handle</span>
&gt;&gt; mjf = <span style="color: #0000FF;">get</span><span style="color: #080;">(</span>handle<span style="color: #080;">(</span><span style="color: #0000FF;">gcf</span><span style="color: #080;">)</span>, <span style="color:#A020F0;">'JavaFrame'</span><span style="color: #080;">)</span>;
&gt;&gt; jWindow = mjf.fHG2Client.getWindow  <span style="color: #228B22;">% or: mjf.getAxisComponent.getTopLevelAncestor</span>
jWindow =
com.mathworks.hg.peer.FigureFrameProxy$FigureFrame[fClientProxyFrame,740,-761,576x509,...]
&nbsp;
<span style="color: #228B22;">% Try to remove decoration</span>
&gt;&gt; jWindow.setUndecorated(<span style="color: #0000FF;">true</span>)
<span style="color: #F00;">Java exception occurred:
java.awt.IllegalComponentStateException: The frame is displayable.
	at java.awt.Frame.setUndecorated(Unknown Source)</span></pre>
</div>
</div>
<p>On the other hand, if we try to call <i>setUndecorated</i> on a new invisible figure then we&#8217;d see that the <code>JFrame</code> component is not yet created by Matlab:</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Create a simple Matlab figure</span>
hFig = <span style="color: #0000FF;">figure</span><span style="color: #080;">(</span><span style="color:#A020F0;">'Name'</span>,<span style="color:#A020F0;">'Plot example'</span>, <span style="color:#A020F0;">'Visible'</span>,<span style="color:#A020F0;">'off'</span><span style="color: #080;">)</span>;
&nbsp;
<span style="color: #228B22;">% Get the underlying Java JFrame reference handle (empty)</span>
&gt;&gt; mjf = <span style="color: #0000FF;">get</span><span style="color: #080;">(</span>handle<span style="color: #080;">(</span>hFig<span style="color: #080;">)</span>,<span style="color:#A020F0;">'JavaFrame'</span><span style="color: #080;">)</span>;
&gt;&gt; jWindow = mjf.getAxisComponent.getTopLevelAncestor
jWindow =
     <span style="color: #080;">[</span><span style="color: #080;">]</span>
&gt;&gt; jWindow = mjf.fHG2Client.getWindow
jWindow =
     <span style="color: #080;">[</span><span style="color: #080;">]</span>
&nbsp;
&gt;&gt; jWindow.setUndecorated<span style="color: #080;">(</span><span style="color: #0000FF;">true</span><span style="color: #080;">)</span>
<span style="color: #F00;">Attempt to reference field of non-structure array.</span></pre>
</div>
</div>
<p>So we have a catch-22 situation: we can&#8217;t call <i>setUndecorated</i> until the <code>JFrame</code> is created, but Matlab only creates it when it displays the figure window, and then it&#8217;s too late to undecorate&#8230;</p>
<h3 id="2">Attempt #2 &#8211; reparenting: an optical illusion</h3>
<p>One way that I found around this problem is to reparent the Matlab <code>JFrame</code>&#8216;s content onto a pure Java <code>JFrame</code> that has been made undecorated. To hide the Matlab figure after creating the <code>JFrame</code>, we can simply move the figure&#8217;s position to be outside the visible monitor area:</p>
<pre lang='matlab'>
% Create a simple Matlab figure (visible, but outside monitor area)
t = 0 : 0.01 : 10;
hFig = figure('Name','Plot example', 'ToolBar','none', 'MenuBar','none');
hLine = plot(t, cos(t));
hButton = uicontrol('String','Close', 'Position',[307,0,45,16]);
% Ensure that everything is rendered, otherwise the following will fail
drawnow;
% Get the underlying Java JFrame reference handle
mjf = get(handle(hFig), 'JavaFrame');
jWindow = mjf.fHG2Client.getWindow;  % or: mjf.getAxisComponent.getTopLevelAncestor
% Get the content pane's handle
mjc = jWindow.getContentPane;
mjr = jWindow.getRootPane;  % used for the offset below
% Create a new pure-Java undecorated JFrame
figTitle = jWindow.getTitle;
jFrame = javaObjectEDT(javax.swing.JFrame(figTitle));
jFrame.setUndecorated(true);
% Move the JFrame's on-screen location just on top of the original
jFrame.setLocation(mjc.getLocationOnScreen);
% Set the JFrame's size to the Matlab figure's content size
%jFrame.setSize(mjc.getSize);  % slightly incorrect by root-pane's offset
jFrame.setSize(mjc.getWidth+mjr.getX, mjc.getHeight+mjr.getY);
% Reparent (move) the contents from the Matlab JFrame to the new JFrame
jFrame.setContentPane(mjc);
% Make the new JFrame visible
jFrame.setVisible(true);
% Hide the Matlab figure by moving it off-screen
pos = get(hFig,'Position');
set(hFig, 'Position',[-1000,-1000,pos(3:4)]);
drawnow;
</pre>
<p>Matlab figures are not pure <code>JFrame</code> but rather a subclass (<code>com.mathworks.widgets.desk.DTSingleClientFrame</code>). So instead of creating a new <code>JFrame</code>, we could create a new instance of Matlab&#8217;s class instead, potentially solving a few problems:</p>
<pre lang='matlab'>
jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance;
jFrame = javaObjectEDT(com.mathworks.widgets.desk.DTSingleClientFrame(jDesktop, figTitle));
% ...the rest is exactly the same as above...
</pre>
<p>Either way, we now get a nice undecorated window containing our Matlab contents (see screenshot above).<br />
Once the undecorated <code>JFrame</code> becomes visible, we should not hide or delete the original Matlab figure, because this will stop rendering of the contents.</p>
<h3 id="customizing">Working with the undecorated frame</h3>
<p>We can modify the Matlab figure and its contents normally, just as if they still appeared within the original Matlab figure. This can be used to display a dynamic application splash-screen, that displays information on various initialization/loading steps. Or alternately we could use it to display a system health-monitor (small panel with red/green indicators), or maybe a graph with streaming market data or live news alerts. The usages are endless, limited only by your imagination, <u>not</u> by Matlab.<br />
For example, let&#8217;s modify our plot dynamically using a timer, and set the close button&#8217;s callback to dismiss the new <code>JFrame</code> and original figure:</p>
<pre lang='matlab'>
% Set a timer to dynamically update the plot every 0.1 sec
start(timer('TimerFcn', {@timerCallback,hLine}, 'ExecutionMode','fixedRate', 'Period',0.1));
% Set the close button callback
set(hButton, 'Callback',{@closeCallback,jFrame});
% This is the close button's callback
function closeCallback(hButton, eventData, jFrame)
   delete(ancestor(hButton,'figure'));
   dispose(jFrame);
end
% This is the plot timer's callback
function timerCallback(hTimer, eventData, hLine)
   xdata = get(hLine,'XData') + 0.1;
   set(hLine, 'XData',xdata, 'YData',cos(xdata));
   xlim([min(xdata) max(xdata)]);
end
</pre>
<p>Note: if you don&#8217;t hide the toolbar/menubar in the original Matlab figure, some of their functions will not work properly in the new <code>JFrame</code> (e.g., zoom, pan etc.). But in most use-cases we do not want a toolbar/menubar in an undecorated window. The example above showed an undecorated window without the toolbar/menubar.<br />
If we wish to avoid having the new <code>JFrame</code> appear in the Operating System&#8217;s taskbar, we can use the following command:</p>
<pre lang='matlab'>jFrame.setType(javaMethod('valueOf','java.awt.Window$Type','UTILITY'))</pre>
<p>Note that this command must be executed <u>before</u> the <code>JFrame</code> is made visible. Also note that it only works with Java 7, in other words Matlab R2013b (8.2) or newer (or if you are very adventurous and happen to use an older Matlab with a custom Java 7 installation).<br />
But now that there is no taskbar component, how can we transfer focus to our new undecorated window? In other words, if another windows hides our new undecorated frame, how can we get it back on top?<br />
A simple solution is to set the Matlab figure frame&#8217;s <b>FocusGainedCallback</b> to <i>requestFocus</i> for the newly created <code>jFrame</code>. Then, when we click the Matlab figure&#8217;s button on the taskbar, the new <code>jFrame</code> will pop into focus. In effect, this provides the optical illusion that the taskbar button refers to the undecorated window (since the actual Matlab figure is positioned beyond the monitor&#8217;s area):</p>
<pre lang='matlab'>
hjWindow = handle(jWindow, 'CallbackProperties');
set(hjWindow, 'FocusGainedCallback', @(h,e)jFrame.requestFocus);
</pre>
<p>Likewise, we should instrument our Matlab figure so that when it is closed/deleted, so too is our new <code>jFrame</code>:</p>
<pre lang='matlab'>set(hjWindow, 'WindowClosedCallback', @(h,e)jFrame_.dispose);</pre>
<h3 id="undecorateFig">undecorateFig and redecorateFig</h3>
<p>I have encapsulated all of the above in a couple of very easy-to-use utilities that I just <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/50111-undecoratefig-remove-restore-figure-border-and-title-bar">posted on the Matlab File Exchange</a>: <i><b>undecorateFig</b></i>, <i><b>redecorateFig</b></i>. Using them can&#8217;t get any simpler than this:</p>
<pre lang='matlab'>
undecorateFig;        % undecorate the current figure (gcf)
undecorateFig(hFig);  % hFig is any GUI handle (needs to be visible)
redecorateFig;        % redecorate the current figure (gcf)
redecorateFig(hFig);  % hFig is any GUI handle
</pre>
<blockquote><p>Any sufficiently advanced technology is indistinguishable from magic – Arthur C. Clarke &nbsp; 🙂</p></blockquote>
<p>Have you made some interesting use of this nice feature in your application? If so, please share it in a comment below.<br />
A suggested related mini project for anyone interested: add an <a target="_blank" rel="nofollow" href="http://google.com/search?q=reflection&#038;tbm=isch">image reflection</a> of the current figure contents beneath the figure. You could use my <a target="_blank" href="/articles/screencapture-utility"><i><b>ScreenCapture</b></i></a> utility or directly use <a target="_blank" rel="nofollow" href="http://www.java2s.com/Code/JavaAPI/java.awt/RobotcreateScreenCaptureRectanglescreenRect.htm"><code>java.awt.Robot.createScreenCapture(mjc.getLocationOnScreen)</code></a>, process the resulting image (blur, apply transparency gradient, crop at 50% height etc.) and place the resulting image within an undecorated <code>JFrame</code> placed directly beneath the main figure. You can instrument the figure (<code>hjWindow</code>)&#8217;s <b>ComponentMovedCallback</b> and <b>ComponentResizedCallback</b> to move/resize the reflection <code>JFrame</code> whenever the parent figure moves or is resized. You could use a timer to periodically update the reflection image so that it remains synchronized with the parent. You&#8217;ll probably also want to add a nice toggle-button to the figure&#8217;s toolbar to turn the reflection on/off. Maybe I&#8217;ll hack this project someday when I have some spare time. Or maybe someone will beat me to it&#8230; Care to try?</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/frameless-undecorated-figure-windows">Frameless (undecorated) figure windows</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/figure-window-customizations" rel="bookmark" title="Figure window customizations">Figure window customizations </a> <small>Matlab figure windows can be customized in numerous manners using the underlying Java Frame reference. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/blurred-matlab-figure-window" rel="bookmark" title="Blurred Matlab figure window">Blurred Matlab figure window </a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/minimize-maximize-figure-window" rel="bookmark" title="Minimize/maximize figure window">Minimize/maximize figure window </a> <small>Matlab figure windows can easily be maximized, minimized and restored using a bit of undocumented magic powder...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/frameless-undecorated-figure-windows/feed</wfw:commentRss>
			<slash:comments>12</slash:comments>
		
		
			</item>
		<item>
		<title>Unorthodox checkbox usage</title>
		<link>https://undocumentedmatlab.com/articles/unorthodox-checkbox-usage?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=unorthodox-checkbox-usage</link>
					<comments>https://undocumentedmatlab.com/articles/unorthodox-checkbox-usage#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 14 Jan 2015 21:41:18 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Optical illusion]]></category>
		<category><![CDATA[uicontrol]]></category>
		<category><![CDATA[uisplitpane]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5457</guid>

					<description><![CDATA[<p>There are various ways to display interactive split-panes in Matlab GUI. Uiextras flex-panels override a checkbox control's CData to display a divider. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/unorthodox-checkbox-usage">Unorthodox checkbox usage</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/tri-state-checkbox" rel="bookmark" title="Tri-state checkbox">Tri-state checkbox </a> <small>Matlab checkboxes can easily be made to support tri-state functionality....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/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="https://undocumentedmatlab.com/articles/transparency-in-uicontrols" rel="bookmark" title="Transparency in uicontrols">Transparency in uicontrols </a> <small>Matlab uicontrols' CData property can be customized to provide background transparency....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-editbox-scrollbars" rel="bookmark" title="Customizing listbox &amp; editbox scrollbars">Customizing listbox &amp; editbox scrollbars </a> <small>Matlab listbox and multi-line editbox uicontrols have pre-configured scrollbars. This article shows how they can be customized....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A few weeks ago, Robert Cumming <a target="_blank" href="/articles/transparency-in-uicontrols">explained</a> how we can use a Matlab uicontrol&#8217;s <b>CData</b> property to provide an optical illusion of a transparent background. Today I will discuss another usage of this property, providing a simple checkbox control the unorthodox appearance of a split-pane divider.<br />
The underlying problem description is easy: we wish to have the ability to split a Matlab uipanel into two or more sub-panels, separated by a draggable horizontal/vertical divider. Such split-panes are standard in any semi-decent GUI, but for some reason were never incorporated in official Matlab. This is a real pity, but not to worry as there are at least two alternatives we could use:</p>
<h3 id="UISplitPane">UISplitPane</h3>
<p><i><b>UISplitPane</b></i> is a <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/23073-uisplitpane-split-a-container--figure-frame-uipanel--into-two-resizable-sub-containers">utility</a> that I wrote back in 2009 that uses a Java <code><a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/splitpane.html">JSplitPane</a></code> divider and associates it with plain Matlab panels on both sides. This solves the problem of embedding Matlab axes in Java panels, such as the ones provided by the standard Java <code>JSplitPane</code>. A detailed description of the technique can be found in my <a target="_blank" href="/articles/uisplitpane">dedicated post</a> on this utility.<br />
<figure id="attachment_120" aria-describedby="caption-attachment-120" style="width: 400px" class="wp-caption alignright"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/blog/wp-content/uploads/2009/03/uisplitpane_animated.gif" alt="Two levels of UISplitPane, with customized dividers" title="Two levels of UISplitPane, with customized dividers" width="400" height="354" class="size-full wp-image-120" /><figcaption id="caption-attachment-120" class="wp-caption-text">Two levels of UISplitPane, with customized dividers</figcaption></figure></p>
<pre lang='matlab'>[hDown,hUp,hDiv1] = uisplitpane(gcf, 'Orientation','ver', 'dividercolor',[0,1,0]);
[hLeft,hRight,hDiv2] = uisplitpane(hDown, 'dividercolor','r', 'dividerwidth',3);
t=0:.1:10;
hax1=axes('Parent',hUp);    plot(t,sin(t));
hax2=axes('parent',hLeft);  plot(t,cos(t));
hax3=axes('parent',hRight); plot(t,tan(t));
hDiv1.DividerLocation = 0.75;    % one way to modify divider properties...
set(hDiv2,'DividerColor','red'); % ...and this is another way...
</pre>
<p><span id="more-5457"></span><br />
Making <i><b>UISplitPane</b></i> work in HG2 (R2014b onward) was quite a pain: numerous changes had to be made. For example, dynamic UDD properties can no longer be added to Matlab handles, only to Java ones. For Matlab handles, we now need to use the <i><b>addprop</b></i> function. For such properties, the UDD meta-property <code>SetFunction</code> is now called <code>SetMethod</code> (and similarly for Get) and only accepts function handles (not function handle cells as in UDD). Also, the UDD meta-property <code>AccessFlags.PublicSet='off'</code> needed to change to <code>SetAccess='private'</code>. Also, <b><i>handle.listener</b></i> no longer works; instead, we need to use the <i><b>addlistener</b></i> function. There are quite a few other similar tweaks, but <i><b>UISplitPane</b></i>now hopefully works well on both old (HG1, R2014a and earlier) and new (HG2, R2014b+) Matlab releases. Let me know if you still see unhandled issues.</p>
<h3 id="uiextras">UIExtras flex-box</h3>
<p>UIExtras (officially named &#8220;GUI Layout Toolbox&#8221;) is a toolbox of very useful GUI handling functions related to layout management. Written within MathWorks and originally posted in 2010, it has been under continuous maintenance ever since. While being called a &#8220;toolbox&#8221;, it is in fact freely-downloadable from the Matlab File Exchange.<br />
The new HG2 introduced in R2014b did not just make code porting difficult for me &#8211; uiextras&#8217; developers (MathWorkers Ben Tordoff and David Sampson) also encountered great difficulties in porting the code and making sure that it is backward compatible with HG1. In the end they gave up and we now have two distinct versions of the toolbox: the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/27758-gui-layout-toolbox">original version for HG1</a> (R2014a and earlier) and a <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/47982-gui-layout-toolbox">new version for HG2</a> (R2014b+).<br />
In my opinion, uiextras is one of the greatest examples of Matlab code on the File Exchange. It is well-written, well-documented and highly performant (although I would also have preferred it to be a bit more robust, it sometimes complains when used). Readers could benefit greatly by studying its techniques, and today&#8217;s subject topic is one such example. Specifically, the split-pane divider in uiextras (used by HBoxFlex and VBoxFlex) is simply a Matlab uicontrol having a custom <b>CData</b> property. This <b>CData</b> value is computed and set programmatically (at the bottom of <i><b><a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/47982-gui-layout-toolbox/content//layout/+uix/Divider.m">uix.Divider</a></b></i>) to display a flat color with some markings at the center (&#8220;hand-holds&#8221;, a visual cue for interactive dragging, which can be turned off if requested). Thus, for a vertical divider (for an HBoxFlex container) of height 100 pixels and width of 5 pixels, we would get a <b>CData</b> of 100x5x3 (x3 for RGB colors):</p>
<pre lang='matlab'>
hHBox = uiextras.HBoxFlex('Spacing',6, 'BackgroundColor','b');  % Spacing=6 means divider width =6px, and CData width =5px
hLeft  = uicontrol('parent',hHBox, 'style','check', 'string','Left split pane');
hRight = uicontrol('parent',hHBox, 'style','radio', 'string','Right split pane');
</pre>
<p><center><figure style="width: 335px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="UIExtras HBoxFlex with draggable split-pane divider" src="https://undocumentedmatlab.com/images/UIExtras_HBoxFlex.png" title="UIExtras HBoxFlex with draggable split-pane divider" width="335" height="190" /><figcaption class="wp-caption-text">UIExtras HBoxFlex with draggable split-pane divider</figcaption></figure></center><br />
The divider handle is a private property, so we cannot readily access it. However, as I have <a target="_blank" href="/articles/accessing-private-object-properties">explained</a> last year, we can use the builtin <i><b>struct</b></i> function:</p>
<pre lang='matlab'>
oldWarn = warning('off','MATLAB:structOnObject');  % temporarily disable warning message on discouraged usage
hHBox_data = struct(hHBox);  % this includes hidden/private properties
warning(oldWarn);
hDividers = hHBox_data.Dividers;  % multiple dividers are possible in HBoxFlex/VBoxFlex
cdata = get(hDividers(1), 'CData');
</pre>
<p>A very nice trick here is that this divider uicontrol is <i>not</i> a pushbutton as we might have expected. Instead, it is a checkbox control. And while it does not look anything like a standard checkbox (due to the custom <b>CData</b>), checkboxes (and radio-buttons) have a very important advantage that caused them to be preferable over buttons: in buttons, there is always a small border showing at the control&#8217;s edges, but checkboxes do not have any 3D appearance, or in other words they do not have a border &#8212; their <b>CData</b> can span the entire extent of the control. Neat, right?<br />
This enables us to customize the appearance of checkboxes (and radios) to any arbitrary shape, by setting the relevant <b>CData</b> pixels to transparent/bgcolor (as Robert showed last week for buttons). Matlab GUI controls no longer need to look a boring rectangle. We can have clickable stars, draggable icons, and other similar uses. This really opens up the possibilities for rich GUI appearance. If anyone uses this feature, please do post a comment below (preferably with a nice screenshot!).</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/unorthodox-checkbox-usage">Unorthodox checkbox usage</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/tri-state-checkbox" rel="bookmark" title="Tri-state checkbox">Tri-state checkbox </a> <small>Matlab checkboxes can easily be made to support tri-state functionality....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/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="https://undocumentedmatlab.com/articles/transparency-in-uicontrols" rel="bookmark" title="Transparency in uicontrols">Transparency in uicontrols </a> <small>Matlab uicontrols' CData property can be customized to provide background transparency....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-editbox-scrollbars" rel="bookmark" title="Customizing listbox &amp; editbox scrollbars">Customizing listbox &amp; editbox scrollbars </a> <small>Matlab listbox and multi-line editbox uicontrols have pre-configured scrollbars. This article shows how they can be customized....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/unorthodox-checkbox-usage/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Transparency in uicontrols</title>
		<link>https://undocumentedmatlab.com/articles/transparency-in-uicontrols?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=transparency-in-uicontrols</link>
					<comments>https://undocumentedmatlab.com/articles/transparency-in-uicontrols#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 10 Dec 2014 18:00:34 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Optical illusion]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Robert Cumming]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5302</guid>

					<description><![CDATA[<p>Matlab uicontrols' CData property can be customized to provide background transparency.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/transparency-in-uicontrols">Transparency in uicontrols</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/images-in-matlab-uicontrols-and-labels" rel="bookmark" title="Images in Matlab uicontrols &amp; labels">Images in Matlab uicontrols &amp; labels </a> <small>Images can be added to Matlab controls and labels in a variety of manners, documented and undocumented. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/panel-level-uicontrols" rel="bookmark" title="Panel-level uicontrols">Panel-level uicontrols </a> <small>Matlab's uipanel contains a hidden handle to the title label, which can be modified into a checkbox or radio-button control...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/icon-images-in-matlab-uicontrols" rel="bookmark" title="Icon images &amp; text in Matlab uicontrols">Icon images &amp; text in Matlab uicontrols </a> <small>HTML can be used to add image icons to Matlab listbox and popup (drop-down) controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" rel="bookmark" title="Plot markers transparency and color gradient">Plot markers transparency and color gradient </a> <small>Matlab plot-line markers can be customized to have transparency and color gradients. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I would like to welcome back guest blogger Robert Cumming, an independent UK contractor who developed a commercial class-based <a target="_blank" rel="nofollow" href="https://sites.google.com/site/matpihome/matlab-gui-framework">Matlab GUI framework</a>. Today, Robert will highlight how he customized the use of uicontrol <b>CData</b> property.</i><br />
Before detailing how I used this feature I will start with a basic example.  A number of times (see <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/answers/7928-matlab-gui-set-transparent-background-color-for-components">example1</a>, <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/169067">example2</a>), users have asked is it possible to set the background of uicontrols to be transparent?<br />
There are a number of reasons why we might want to do this. For example, we might wish to display a clickable image, and don&#8217;t want its background (which is typically white) to be displayed. To place on image on a uicontrol we use its <b>CData</b> property, which according to the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/uicontrol-properties.html">official Matlab documentation</a> must be a 3-D array of truecolor RGB values.<br />
Let&#8217;s start with a simple example:<br />
<figure style="width: 260px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="uicontrol with white bgcolor" src="https://undocumentedmatlab.com/images/CData1.jpg" title="uicontrol with white bgcolor" width="260" height="225" /><figcaption class="wp-caption-text">uicontrol with white bgcolor</figcaption></figure></p>
<pre lang='matlab'>
f = figure;
img = imread('Matlab_Logo.png');
s = size(img);
pb = uicontrol('Style','pushbutton', 'Position',[10 10 s(2) s(1)], 'CData',img, ...
               'Callback',@(a,b)disp('push button'), 'BackgroundColor','green');
</pre>
<p>The code above produces the figure on the right; when we click on the image, the pushbutton callback is executed.<br />
However the background of the button is white. This is because the image is MxNx3 rectangle the size of the button.<br />
We can set the white portion of the image to be transparent so that it will show the background color of the pushbutton (in our example, &#8216;green&#8217;).<br />
First, we read the image and convert it to a 2D <i><b>double</b></i> array that ranges from 0 to 1 (the original image was RGB <i><b>uint8</b></i>, 0 to 255).  Then find the index for each RGB where the value is 1 (white):<br />
<span id="more-5302"></span></p>
<pre lang='matlab'>
img = imread('Matlab_Logo.png');
img = double(img)/255;
index1 = img(:,:,1) == 1;
index2 = img(:,:,2) == 1;
index3 = img(:,:,3) == 1;
</pre>
<p><figure style="width: 260px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="uicontrol with transparent bgcolor" src="https://undocumentedmatlab.com/images/CData2.jpg" title="uicontrol with transparent bgcolor" width="260" height="225" /><figcaption class="wp-caption-text">uicontrol with transparent bgcolor</figcaption></figure><br />
The color (in this example) that we want to make transparent is where all RGB is 1, so calculate a logical index where this is true and update the <code>img</code> variable:</p>
<pre lang='matlab'>
indexWhite = index1+index2+index3==3;
for idx = 1 : 3
   rgb = img(:,:,idx);     % extract part of the image
   rgb(indexWhite) = NaN;  % set the white portion of the image to NaN
   img(:,:,idx) = rgb;     % substitute the update values
end
set(pb, 'CData', img)     % Update the CData variable
</pre>
<p>Updating the <b>CData</b> we get the image with the green background. We could set the Color of the figure to be green, to match the uicontrol&#8217;s background color:</p>
<pre lang='matlab'>set(f, 'Color', get(pb,'BackgroundColor'))</pre>
<h3 id="transparent">Transparent background</h3>
<p>As mentioned <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/answers/7928-matlab-gui-set-transparent-background-color-for-components">here</a>, we can link the <b>CData</b> to a screenshot image of the parent figure.<br />
When we combine the two methods above, we get the effect of the uicontrol background being transparent (the smaller logo is a button that can be clicked):<br />
<figure style="width: 408px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="uicontrol with transparent background (optical illusion)" src="https://undocumentedmatlab.com/images/CData3.jpg" title="uicontrol with transparent background (optical illusion)" width="408" height="380" /><figcaption class="wp-caption-text">uicontrol with transparent background (optical illusion)</figcaption></figure></p>
<pre lang='matlab'>
f = figure(); % create a figure with an axes on it
ax = axes('Units','pixels', 'Position',[0 0 560 420], 'XTick',[], 'YTick',[], ...
          'Nextplot','add', 'YDir','reverse');
% read the big logo image - background of the figure
bigImage = imread('Matlab_LogoBig.png');
image(bigImage, 'parent', ax);  % Display the image in the axes
% read a smaller image - background of button
img = imread('Matlab_Logo.png');
s = size(img);
pos = [10 10 s(2) s(1)];  %Position of the button
% Extract the portion of the image where the button will be.
F = getframe(ax,pos);  % take a screenshot of the parent figure
pb = uicontrol('Style','pushbutton', 'Units','pixels', 'Position',pos, ...
               'Callback',@(a,b)disp('push button'));
% as before - calculate where the button image is white.
img = double(img)/255;
index1 = img(:,:,1) == 1;
index2 = img(:,:,2) == 1;
index3 = img(:,:,3) == 1;
indexWhite = index1+index2+index3==3;
% for each pixel, replace the white portion with the parent image data
for idx = 1 : 3
   rgb = 1-img(:,:,idx);                   % To make the picture quirky change the RGB
   pImage = double(F.cdata(:,:,idx))/255;  % extract part of the image
   rgb(indexWhite) = pImage(indexWhite);   % set the white portion of the image to the parent
   img(:,:,idx) = rgb;                     % substitute the update values
end
% Update the push button image
set(pb, 'CData', img)
</pre>
<h3 id="checkboxes">Customizing checkboxes</h3>
<p>I have shown how to manipulate the <b>CData</b> of a button. Unfortunately, not all uicontrols have a <b>CData</b> property &#8212; the documentation states that pushbuttons and toggle buttons are the only uicontrols that are fully supported. It also mentions that you can use it in radiobuttons and checkboxes, which brings me to how I used it in my application: I use this feature on a checkbox &#8211; to use it properly we need to ensure that the size of the image we put in <b>CData</b> is 16x16x3.  In this case we set a transparent color by setting pixel RGB values to NaN:<br />
<figure style="width: 347px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="uicontrol with transparent bgcolor" src="https://undocumentedmatlab.com/images/CData4.jpg" title="uicontrol with transparent bgcolor" width="347" height="172" /><figcaption class="wp-caption-text">uicontrol with transparent bgcolor</figcaption></figure></p>
<pre lang='matlab'>
f = figure('Color','red');
smiley = imread('smiley.png');
smiley = double(smiley)/255;
index1 = smiley(:,:,1) == 1;
index2 = smiley(:,:,2) == 1;
index3 = smiley(:,:,3) == 1;
indexWhite = index1+index2+index3==3;
% Create a first smiley which has the white background.
uicontrol('Style','checkbox', 'Position',[25 50 16, 16], 'CData',smiley, ...
          'Callback',@(a,b)disp('-1 smiley'));
% For each pixel, replace the white portion with the parent image data
for idx = 1 : 3
   rgb = smiley(:,:,idx);  % To make the picture quirky change the RGB
   rgb(indexWhite) = NaN;
   smiley(:,:,idx) = rgb;  % substitute the update values.
end
% Create a second smiley which has the transparent background.
uicontrol('Style','checkbox', 'Position',[25 25 16, 16], 'CData',smiley, ...
          'Callback',@(a,b)disp('+1 smiley'), 'BackgroundColor','red');
</pre>
<p>The upper smiley is the original image; the lower smiley has its white pixels set to NaN, and the background colors of the control and the figure set to equal. The checkbox has no text is displayed, the user just clicks on the smiley to invoke the callback.<br />
Note: This trick works in R2014b but I have deliberately used old style <i><b>set</b></i> and <i><b>get</b></i> commands for compatibility with older versions of Matlab. I have used this in all versions from R2008a onwards, and I suspect it probably works in older versions as well.<br />
I used this feature several times in my Matlab GUI Toolbox. One of the uses was to create a pin for locking a dynamic panel in position: The panel is by default hidden; when the user hovers the mouse near the edge, the dynamic panel appears after some predefined time (2 seconds). A checkbox with a manipulated <b>CData</b> masquerades as a pin for locking the panel in position. When the panel is pinned, the <b>CData</b> changes accordingly:<br />
<center><img decoding="async" alt="transparent uicontrol usage example" src="https://undocumentedmatlab.com/images/panel_pin.png" title="transparent uicontrol usage example" width="90%" style="max-width:889px;" /><br />
transparent uicontrol usage example</center></p>
<h3 id="Conclusions">Conclusions</h3>
<p>1. The <b>CData</b> property of a uicontrol can be set to NaN to imitate transparent behavior.<br />
2. By linking this with the parent <b>CData</b> we can super-impose an image on top of  another image.<br />
3. We can customize other uicontrols using the method to turn checkboxes (for example) into clickable images.<br />
Have you used this feature?  If so please share in a comment below.<br />
<i><u>Editor&#8217;s note</u>: I have shown another alternative for displaying clickable transparent images in my article on <a target="_blank" href="/articles/displaying-animated-gifs">displaying animated/transparent GIFs</a>. Readers might also find interest in the related article on <a target="_blank" href="/articles/transparent-uipanels">transparent uipanels</a>. Next week I plan to show how MathWorkers Ben Tordoff and David Sampson coerced a simple checkbox uicontrol to have a radically different appearance, as flex-panel dividers in their GUI Layout Toolbox, similarly to what Robert explained today. Stay tuned! &nbsp;&#8211; Yair</i></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/transparency-in-uicontrols">Transparency in uicontrols</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/images-in-matlab-uicontrols-and-labels" rel="bookmark" title="Images in Matlab uicontrols &amp; labels">Images in Matlab uicontrols &amp; labels </a> <small>Images can be added to Matlab controls and labels in a variety of manners, documented and undocumented. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/panel-level-uicontrols" rel="bookmark" title="Panel-level uicontrols">Panel-level uicontrols </a> <small>Matlab's uipanel contains a hidden handle to the title label, which can be modified into a checkbox or radio-button control...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/icon-images-in-matlab-uicontrols" rel="bookmark" title="Icon images &amp; text in Matlab uicontrols">Icon images &amp; text in Matlab uicontrols </a> <small>HTML can be used to add image icons to Matlab listbox and popup (drop-down) controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" rel="bookmark" title="Plot markers transparency and color gradient">Plot markers transparency and color gradient </a> <small>Matlab plot-line markers can be customized to have transparency and color gradients. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/transparency-in-uicontrols/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>HG2 update</title>
		<link>https://undocumentedmatlab.com/articles/hg2-update?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=hg2-update</link>
					<comments>https://undocumentedmatlab.com/articles/hg2-update#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 16 May 2013 00:38:19 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[JavaFrame]]></category>
		<category><![CDATA[Optical illusion]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Undocumented property]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3789</guid>

					<description><![CDATA[<p>HG2 appears to be nearing release. It is now a stable mature system. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/hg2-update">HG2 update</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-rulers" rel="bookmark" title="Customizing axes rulers">Customizing axes rulers </a> <small>HG2 axes can be customized in numerous useful ways. This article explains how to customize the rulers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-liminclude-properties" rel="bookmark" title="Plot LimInclude properties">Plot LimInclude properties </a> <small>The plot objects' XLimInclude, YLimInclude, ZLimInclude, ALimInclude and CLimInclude properties are an important feature, that has both functional and performance implications....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels" rel="bookmark" title="Customizing axes part 5 &#8211; origin crossover and labels">Customizing axes part 5 &#8211; origin crossover and labels </a> <small>The axes rulers (axles) can be made to cross-over at any x,y location within the chart. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-2" rel="bookmark" title="Customizing axes part 2">Customizing axes part 2 </a> <small>Matlab HG2 axes can be customized in many different ways. This article explains some of the undocumented aspects. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Exactly three years ago, I posted information (<a target="_blank" href="/articles/matlab-hg2/">here</a> and <a target="_blank" href="/articles/new-information-on-hg2/">here</a>) about Matlab&#8217;s upcoming new graphics engine, so-called HG2 (<i>Handle Graphics version 2</i>). At the time, I was sure that HG2 was just around the corner. But three years and six releases have passed, Matlab 7 turned into Matlab 8, and HG1 is still in use. I decided that it was time to revisit the latest state of HG2, as reflected in the latest release, R2013a (Matlab 8.1).<br />
In the past few years, development of HG2 has apparently progressed to a stage where most of the kinks were ironed out. The latest HG2 appears to be quite stable, and in my experience most GUI/graphics utilities run as-is, without any need for tweaking. This is good news, which leads me to think that HG2 will be released soon. It is possible that this could happen as early as the upcoming release (R2013b, 8.2) but I have a gut feeling that it will be in R2014a. I also have a gut feeling that MathWorks will name that release 9.0 rather than 8.3, in keeping with its arch-rival <a target="_blank" rel="nofollow" href="http://www.wolfram.com/mathematica/">Mathematica</a>.<br />
HG2 has improved grid lines, plot anti-aliasing and customizable everything (more on this below). Here&#8217;s a simple plot line as it appears in both HG1 and HG2:</p>
<pre lang='matlab'>
hFig = figure('pos',[100,100,300,250]);
x = -10:0.1:10;
y = 1e7*sin(x)./x;
hLine = plot(x,y);
box off; grid on;
title('HG2 plot');
</pre>
<p><center><figure style="width: 620px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="HG1 plot" src="https://undocumentedmatlab.com/images/HG1_plot.png" title="HG1 plot" width="300" height="325" /><img loading="lazy" decoding="async" alt="HG2 plot" src="https://undocumentedmatlab.com/images/HG2_plot.png" title="HG2 plot" width="300" height="325" /><figcaption class="wp-caption-text">Same plot in HG1 and HG2</figcaption></figure></center><br />
We can see that MathWorks has invested heavily in improving usability. The graphics are now much more visually appealing than before. A lot of thought has gone into small details such as the plot colors and the axes gray shades. The changes are small when taken separately, but the overall gestalt is striking. HG2 will definitely justify my license maintenance cost.<br />
<b><u>Addendum Oct 3 2014</u></b>: HG2 is finally released in Matlab release R2014b (8.4 &#8211; not 9.0 as I surmised above). However, many of the advanced customizations shown in this article are still unsupported and undocumented. I plan to detail them in a separate upcoming series of articles.<br />
<span id="more-3789"></span></p>
<h3 id="customizable">Highly customizable</h3>
<p>Matlab in HG2 mode acts and behaves pretty much as you would expect. There are no visible changes to the Desktop or the graphics interface. The major difference is that all graphics handles, whether interactive controls (figure, uicontrols, uitables, etc.) or graph elements (axes, lines, patches, etc.) are instances of class objects (e.g., <code>matlab.ui.Figure</code> or <code>matlab.graphics.chart.primitive.Line</code>) rather than numeric values. This makes it easy to issue commands such as:</p>
<pre lang='matlab'>
hFig.Color = 'w';
hAxes = gca;
hAxes.Title.Color = 'm';  % default: [0,0,0] = black
hAxes.YRuler.SecondaryLabel.String = 'millions';  % original: 'x10^{6}'
hAxes.YRuler.SecondaryLabel.FontAngle = 'italic';  % default: 'normal'
hAxes.YRuler.Axle.LineStyle = 'dotted';  % default: 'solid'
hAxes.YRuler.Axle.ColorData = uint8([0,100,0,255])';  %=dark green; default: [51 51 51 255], corresponding to [0.2 0.2 0.2 1]
hAxes.YBaseline.Color = 'b';  % default: [0.2 0.2 0.2]
hAxes.YBaseline.Visible = 'on';  % default: 'off'
hAxes.XRuler.Axle.Visible = 'off';  % default: 'on'
hLine.Color = [1,0,0];  %='red'
</pre>
<p>rather than using the corresponding <i><b>set(&#8230;)</b></i> or <i><b>get(&#8230;)</b></i> functions, which are still supported for backward compatibility.<br />
<center><figure style="width: 316px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Customized HG2 plot" src="https://undocumentedmatlab.com/images/HG2_plot2.png" title="Customized HG2 plot" width="316" height="342" /><figcaption class="wp-caption-text">Customized HG2 plot</figcaption></figure></center><br />
Notice how much more customizable HG2 is compared to HG1. I am pretty excited from the huge number of additional possible customizations in HG2 compared to HG1. It is real a pity that many of these customizations rely on hidden/undocumented properties (see below). Hopefully this will change when HG2 is officially released.</p>
<h3 id="observations">Some observations</h3>
<p>Here are a few observations that I collected on the latest HG2, as reflected in R2013a:</p>
<ol>
<li>Java is still supported (hurray!). The warnings about the figure&#8217;s <a target="_blank" href="/articles/disable-entire-figure-window/#JavaFrame"><b>JavaFrame</b> property</a> becoming deprecated have fortunately not been fulfilled (hopefully never). All the Java-based GUI tricks shown on this blog and in my book still work, excluding some minor things here and there which are due to inter-release changes rather than to the new HG2 engine.</li>
<li>In order to access the top-level Java <code>Frame</code> of a figure window, we now need to use <code>javaFrame.fHG2Client</code> rather than <a target="_blank" href="/articles/docking-figures-in-compiled-applications/"><code>javaFrame.fHG1Client</code></a>. The relevant code should now look something like this, in order to be fully-compatible with older Matlab releases:
<pre lang='matlab'>
jFrame = get(handle(hFig), 'JavaFrame');
try
    % This works up to R2011a
    jFrame.fFigureClient.setClientDockable(true);
catch
    try
        % This works from R2008b and up, up to HG2
        jFrame.fHG1Client.setClientDockable(true);
    catch
        % This works in HG2
        jFrame.fHG2Client.setClientDockable(true);
    end
end
</pre>
</li>
<li>Anti-aliasing of plot elements (a.k.a. line -smoothing) is now &#8216;on&#8217; by default (double hurray!). Apparently, MathWorks solved the problems with the existing <a target="_blank" href="/articles/plot-linesmoothing-property/">undocumented <b>LineSmoothing</b> property</a>. Still, for some unknown reason, <b>LineSmoothing</b> remains a hidden/undocumented property. Note that for some objects the property name is different. For example, the axes title (which is a <i><b>text</b></i> object of class <code>matlab.graphics.primitive.Text</code>) has a new property called <b>Smoothing</b> that controls anti-aliasing (unlike <b>LineSmoothing</b>, <b>Smoothing</b> appears to be an un-hidden fully-documented property).<br />
<b><u>R2013b addendum</u></b>: The figure handle now includes a property called <b>GraphicsSmoothing</b> that controls anti-aliasing at the entire figure level (default=&#8217;on&#8217;). No more need to set individual graphic elements, although we still can if we want (alas, this flexibility may be removed soon &#8211; see item #6 below). I would have liked to see the anti-aliasing feature use the same property name for all graphic elements, rather than <b>GraphicsSmoothing/LineSmoothing/Smoothing</b>, but maybe I&#8217;m just being an ungrateful spoil-sport&#8230; The good news about <b>GraphicsSmoothing</b> is that this is a <u>non-hidden</u> property. This means it can be seen with <i><b>get</b>(gcf)</i> and once HG2 becomes live it will become fully documented/supported &#8211; hurray!
</li>
<li>Many new properties have been added to graphic objects, that enable customization of different aspects. For example, we can customize the axes grid-lines, containing box and exponent labels in ways that were impossible in HG1 (triple hurray!). Note that many of these new properties are hidden/undocumented (why the hell for???), so we need a utility such as my <a target="_blank" href="/articles/uiinspect/"><i><b>uiinspect</b></i></a> or <a target="_blank" rel="nofollow" href="/articles/getundoc-get-undocumented-object-properties/"><i><b>getundoc</b></i></a> to detect them. Some of the useful new axes properties include <b>*Ruler, *Baseline, *GridHandle, BoxFrame</b> and <b>BackDrop</b> (I showed an example usage of <b>*Ruler</b> and <b>*Baseline</b> above). I have absolutely no idea why these so-useful properties are kept hidden, it simply makes no sense.</li>
<li>Some existing HG1 properties are missing. For example, the <b>UserData</b> property is no longer available for some Java objects (this is a real pity &#8212; I depended on it for many functionalities, such as storing node-specific data in <i><b>uitree</b></i>/<code>JTree</code> nodes). Similarly, axes no longer have <a target="_blank" href="/articles/plot-liminclude-properties/"><b>*LimInclude</b> properties</a> (this actually makes sense &#8211; these properties are still available in plot lines, where they actually have a use).</li>
<li>Some existing HG1 properties now issue a warning, although they still work. For example:
<pre lang='matlab'>
>> hAxes.DrawMode = 'fast';
Warning: The DrawMode property will be removed in a future release.
(Type "warning off MATLAB:hg:willberemoved" to suppress this warning.)
>> hLine.LineSmoothing
Warning: The LineSmoothing property will be removed in a future release.
(Type "warning off MATLAB:hg:willberemoved" to suppress this warning.)
ans =
on
</pre>
<p><b><u>R2013b addendum</u></b>: <code>hAxes.DrawMode</code> no longer issues a warning, although <code>hLine.LineSmoothing</code> does.
</li>
<li>There is an open bug on R2012b and R2013a whereby the <i><b>clf</b></i> function does not delete <a target="_blank" href="/articles/javacomponent/"><i><b>javacomponent</b></i></a> objects. This bug does not affect HG2, where <i><b>clf</b></i> works properly.</li>
<li>Some GUI components are being placed a pixel or two sideways in HG2 compared to HG1. This has no visual importance except in very rare cases, but it does affect my <a target="_blank" href="/articles/findjobj-find-underlying-java-object/"><i><b>findjobj</b></i> utility</a>, which relies on the component&#8217;s position to find its underlying Java object. I have updated <i><b>findjobj</b></i> for the upcoming HG2 and it should work with both HG1 and HG2.</li>
<li>The default axes and labels color has changed from black to gray ([0.2 0.2 0.2]). Grid lines now use an even lighter gray shade. Visually I think that this is a great change, since it directs the viewer&#8217;s focus on the plot contents rather than the external decorations.
	</li>
<li>The default axes plot color order has changed. The standard plot color is no longer blue (as it was for ages in Matlab), but a bluish tint; the second color is no longer red but light green; the third color is reddish rather than dark green, etc.:
<pre lang='matlab'>
% HG1
>> get(0,'defaultAxesColorOrder')
ans =
            0            0            1
            0          0.5            0
            1            0            0
            0         0.75         0.75
         0.75            0         0.75
         0.75         0.75            0
         0.25         0.25         0.25
%HG2
>> get(0,'defaultAxesColorOrder')
ans =
     0.070588      0.40784      0.70196
      0.92941      0.14118      0.14902
      0.60784       0.7451      0.23922
      0.48235      0.17647       0.4549
            1      0.78039            0
      0.30196       0.7451      0.93333
      0.82353       0.4549            0
</pre>
<p><b><u>R2013b addendum</u></b>: The default colors have changed a bit (for the better I think). I still think that the relative order should more closely match the current order (blue-green-red-etc.), for compatibility with existing apps. A small utility function could be added that modifies the color-order to something that may be better suited for color-differentiation (see Tim Holy&#8217;s excellent <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/29702-generate-maximally-perceptually-distinct-colors">utility</a> for an example).
</li>
<li>HG2 axes no longer forget the previous plot color (unless we used <a target="_blank" rel="nofollow" href="http://blogs.mathworks.com/loren/2009/06/03/hold-everything/"><i><b>hold all</b></i></a>) &#8212; in HG2 color cycling is on by default. Note that this causes some visual discrepancies between HG1 and HG2 in plots that use <i><b>hold on</b></i> and have multiple plot lines: In HG1 they were all blue; in HG2 the first is bluish, the second is greenish, then reddish etc.</li>
<li>GUIDE is still the same-ol&#8217; GUIDE (sigh!). The figure toolbar and menubar have likewise not been upgraded, as far as I could tell.</li>
<li>HG2 performance appears to be generally slower than HG1. Hopefully this will improve by the time HG2 is released, since performance has been one of HG1&#8217;s drawbacks all along. In my tests, most GUI/graphic aspects ran only slightly slower in HG2, except for 2D plots that were significantly slower. This is corroborated by running <i><b>bench</b></i>: on my computer, HG1 yields 0.4 for 2D and 0.22 for 3D; in HG2 the performance is 2.1 for 2D and 0.18 for 3D. Looks like the 2D performance still needs some work&#8230;</li>
</ol>
<h3 id="testing">Testing HG2</h3>
<p>As noted in my <a target="_blank" href="/articles/matlab-hg2/">original article</a>, we can start Matlab in HG2 mode by simply adding the startup (command-line) switch <i>-hgVersion 2</i> to the Matlab command (note the space between the <code>-hgVersion</code> and the &#8220;2&#8221;). For example, in Windows, all you need to do is to copy your Matlab shortcut sideways (so that you will always have the standard HG1 version available), then right-click the shortcut, select &#8220;Properties&#8221;, then add <i>-hgVersion 2</i> to the Target field (note the space between &#8220;hgVersion&#8221; and &#8220;2&#8221;). You will probably want to also add the &#8220;HG2&#8221; descriptor to the shortcut name, in the &#8220;General&#8221; tab:<br />
<center><figure style="width: 377px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Matlab startup switch for HG2" src="https://undocumentedmatlab.com/images/HG2_shortcut_props.png" title="Matlab startup switch for HG2" width="377" height="428" /><figcaption class="wp-caption-text">Matlab startup switch for HG2</figcaption></figure></center><br />
If you have any Matlab application that relies on GUI or graphics, I urge you to test it on the new HG2 system. It&#8217;s trivially simple and your application should work exactly the same, or better. If you do detect some incompatibility, please <a href="/articles/hg2-update/#respond">post a comment</a> or <a href="mailto: altmany @gmail.com?subject=HG2 feedback&amp;body=Hi Yair, &amp;cc=;&amp;bcc=" rel="nofollow" target="_blank" onclick="var n='altmany'; var d='gmail.com'; window.open('mailto:'+n+'@'+d+'?subject=HG2 feedback&amp;body=Hi Yair, '); return false;">shoot me an email</a>. In due course I expect that MathWorks will open an official channel for this, but in the meantime I&#8217;ll be sure to pass the information to the relevant person.<br />
Do take a moment for testing HG2 &#8211; we can all contribute to ensure that when HG2 does come out it will be perfect. It&#8217;s in our interest.</p>
<h3 id="NYC_visit">NYC visit</h3>
<p>If you happen to be in New York next week, I urge you to attend the MATLAB Computational Conference on Thursday May 23 (free <a target="_blank" rel="nofollow" href="http://www.mathworks.com/company/events/conferences/matlab-computational-finance-conference-nyc/2013/registration.html">registration</a>; my presentation is scheduled for 4:50pm). I would be happy to meet you to discuss how I could bring value to your needs, either financial-oriented or not. We could meet at the conference, or anywhere in New York on Wednesday May 22 or Friday May 24.<br />
<center><a href="/articles/nyc-visit-may-2013/"><img loading="lazy" decoding="async" title="Matlab Computational Finance Conference - 23 May 2013" src="https://undocumentedmatlab.com/images/conference_invite_animated.gif" alt="Matlab Computational Finance Conference - 23 May 2013" width="324" height="86"/></a></center></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/hg2-update">HG2 update</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-rulers" rel="bookmark" title="Customizing axes rulers">Customizing axes rulers </a> <small>HG2 axes can be customized in numerous useful ways. This article explains how to customize the rulers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-liminclude-properties" rel="bookmark" title="Plot LimInclude properties">Plot LimInclude properties </a> <small>The plot objects' XLimInclude, YLimInclude, ZLimInclude, ALimInclude and CLimInclude properties are an important feature, that has both functional and performance implications....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels" rel="bookmark" title="Customizing axes part 5 &#8211; origin crossover and labels">Customizing axes part 5 &#8211; origin crossover and labels </a> <small>The axes rulers (axles) can be made to cross-over at any x,y location within the chart. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-2" rel="bookmark" title="Customizing axes part 2">Customizing axes part 2 </a> <small>Matlab HG2 axes can be customized in many different ways. This article explains some of the undocumented aspects. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/hg2-update/feed</wfw:commentRss>
			<slash:comments>134</slash:comments>
		
		
			</item>
		<item>
		<title>uiinspect</title>
		<link>https://undocumentedmatlab.com/articles/uiinspect?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=uiinspect</link>
					<comments>https://undocumentedmatlab.com/articles/uiinspect#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 23 Jan 2013 18:00:09 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Dot-Net]]></category>
		<category><![CDATA[JIDE]]></category>
		<category><![CDATA[Optical illusion]]></category>
		<category><![CDATA[UIInspect]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3477</guid>

					<description><![CDATA[<p>uiinspect is a Matlab utility that displays detailed information about an object's methods, properties and callbacks in a single GUI window.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/uiinspect">uiinspect</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/jide-property-grids" rel="bookmark" title="JIDE Property Grids">JIDE Property Grids </a> <small>The JIDE components pre-bundled in Matlab enable creating user-customized property grid tables...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/getting-default-hg-property-values" rel="bookmark" title="Getting default HG property values">Getting default HG property values </a> <small>Matlab has documented how to modify default property values, but not how to get the full list of current defaults. This article explains how to do this. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/findjobj-gui-display-container-hierarchy" rel="bookmark" title="FindJObj GUI &#8211; display container hierarchy">FindJObj GUI &#8211; display container hierarchy </a> <small>The FindJObj utility can be used to present a GUI that displays a Matlab container's internal Java components, properties and callbacks....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/propertiesgui" rel="bookmark" title="propertiesGUI">propertiesGUI </a> <small>propertiesGUI is a utility that presents property-value structs in a convenient table format, useful in Matlab GUIs. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>After several years in which I have mentioned my <i><b>uiinspect</b></i> utility in posts, I figured it is high time to actually describe this utility in detail.<br />
<figure style="width: 500px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="uiinspect in action (Java, HG, COM)" src="https://undocumentedmatlab.com/images/uiinspect.gif" title="uiinspect in action (Java, HG, COM)" width="500" height="387"/><figcaption class="wp-caption-text">uiinspect in action (Java, HG, COM)</figcaption></figure><br />
<i><b>uiinspect</b></i>, <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect">downloadable</a> from the Matlab file Exchange, is a Matlab GUI utility that inspects the specified object and provides detailed information about its super-classes, methods, properties, static fields and callbacks in a unified Matlab window. <i><b>uiinspect</b></i> works on a very wide variety of inputs: Matlab/Java/Dot-Net class names and class objects; COM/DCOM objects, Handle Graphics handles etc.<br />
In essence, <i><b>uiinspect</b></i> incorporates the information presented by the following built-in Matlab functions: <i><b>inspect</b></i>, <i><b>get</b></i>, and <i><b>methodsview</b></i>. <i><b>uiinspect</b></i> also presents additional aspects that are not available in any built-in Matlab function (for example, inheritance information, undocumented hidden properties, properties meta-data, grouping of callbacks by type).<br />
<i><b>uiinspect</b></i> displays hidden properties and fields that are not normally displayed in Matlab (see my related <a target="_blank" href="/articles/getundoc-get-undocumented-object-properties/">getundoc</a> utility). Property meta-data such as type, accessibility, visibility and default value are also displayed. Object properties and callbacks may be modified interactively within the <i><b>uiinspect</b></i> window.<br />
Of over 40 utilities that I have so-far submitted to the File Exchange, <i><b>uiinspect</b></i> is one of my most complex (together with <a target="_blank" href="/articles/findjobj"><i><b>findjobj</b></i></a>). It has undergone 24 revisions since its initial release in 2007. The latest revision has nearly 3000 source-code lines, of which 75% are code lines, 20% are comment lines and the rest are empty spacer lines. That&#8217;s a pretty complex utility to describe, and it relies on plenty of undocumented aspects, so today&#8217;s post will only highlight the important aspects. Readers are more than welcome to have a look at the source code for additional details. It is pretty-well documented, if I may say so myself.<br />
<span id="more-3477"></span></p>
<h3 id="syntax">Usage syntax</h3>
<p>The basic syntax is:</p>
<pre lang='matlab'>hFig = uiinspect(handle)</pre>
<p>Examples:</p>
<pre lang='matlab'>
hFig = uiinspect(0);                         % the root handle
hFig = uiinspect(handle(0));
hFig = uiinspect(gcf);                       % current figure
hFig = uiinspect(handle(gcf));
uiinspect('java.lang.String');               % Java classname
uiinspect(java.lang.String('yes'));          % Java object
uiinspect(get(gcf,'JavaFrame'));             % Java object
uiinspect(classhandle(handle(gcf)));         % UDD class object
uiinspect(findprop(handle(gcf),'MenuBar'));  % UDD property
uiinspect(actxserver('Excel.Application'));  % COM object
uiinspect(Employee)                          % Matlab class object
uiinspect(?handle)                           % Matlab metaclass object
uiinspect('meta.class')                      % Matlab class name
uiinspect(System.DateTime.Now)               % Dot-Net object
</pre>
<p><i><b>uiinspect</b></i> returns a handle to the created figure window. <i><b>uiinspect</b></i> opens a regular Matlab figure window which may be accessed via hFig (unlike Matlab&#8217;s <i><b>methodsview</b></i> and <i><b>inspect</b></i> functions which open Java frame that is not accessible from Matlab).<br />
Unlike Matlab&#8217;s functions, multiple <i><b>uiinspect</b></i> windows can be opened simultaneously, for different objects. The differentiation is done based on figure title, which contains the inspected object&#8217;s name (if available) and its class &#8211; reinspecting the same object will reuse the existing figure window, but in all other cases a new figure window will be created.</p>
<h3 id="panels">Main panels</h3>
<p><i><b>uiinspect</b></i> includes the following information panels, that shall be described separately below:</p>
<ul>
<li>Class information (including superclasses, if applicable)</li>
<li>Methods (for objects) or graphic handle hierarchy (for Handle Graphics)</li>
<li>Callbacks (where applicable)</li>
<li>Inspectable properties</li>
<li>Other properties plus full meta-data (where applicable)</li>
</ul>
<p>The panels are fully resizable. We can drag the divider lines up/down or left/right and the contents automatically adjust accordingly. Each panel has a minimal viewable width/height, and the dividers cannot be dragged to squeeze the panels below these minimums &#8211; they can only be minimized, which hides the relevant panel entirely. To minimize a panel, simply click the relevant small arrow mark on the divider. The opposite arrow mark next to it maximizes the panel, effectively minimizing the panel on the other side. Once minimized/maximized, the divider can be restored by simply clicking it once, or by dragging it (again, panel minimum sizes apply).<br />
<i><b>uiinspect</b></i> only uses Java panels, so implementing the dividers required use of the simple <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/splitpane.html">JSplitPane</a>. In a general case where we might wish to embed Matlab graphs in one of the side panels, we would need to employ a more sophisticated solution (see my <a target="_blank" href="/articles/uisplitpane/">UISplitPane</a> utility).</p>
<h3 id="class">Class information</h3>
<p>The top-left panel displays a label with information about the object&#8217;s class and super-classes inheritance (where applicable).<br />
The class name itself is hyper-linked to the class&#8217;s documentation: if this is a standard Java class, then to the official online javadoc for this class which opens up in Matlab&#8217;s internal web browser. In fact, since different Matlab releases use different JVM versions (1.3 through 1.6), the link points to the documentation page corresponding to the JVM version actually used.<br />
If the class is non-Java, the hyperlink displays the class&#8217;s help section in Matlab&#8217;s Command Window / console. The panel&#8217;s tooltip displays the same information in a slightly different manner.<br />
The hyperlink in the label is actually an optical illusion. In fact, the entire label is hyper-linked, and clicking any part of it will display the relevant documentation (a similar optical illusion is used to display the hyperlink at the footer of the utility window). The illusion is achieved using <a target="_blank" href="/articles/html-support-in-matlab-uicomponents/">Matlab&#8217;s HTML formatting</a>, where the part of the label string consisting of the class name is underlined. The cursor was dynamically modified to a pointed hand-finger when the mouse hovers over the label, using the following simple Java-based command:</p>
<pre lang='matlab'>methodsLabel.setCursor(java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));</pre>
<p>Special treatment is done to extract the class&#8217;s superclass, the interfaces that it implements and any possible class qualifiers (for example, &#8220;final&#8221;).<br />
For those interested to dig within the code, all this is done in <i><b>uiinspect</b></i>&#8216;s <i>getMethodsPane</i> function.<br />
Next to the class label, a checkbox is presented (&#8220;Extra&#8221;). Clicking this checkbox displays additional meta-data information (qualifiers, interrupts and inheritance) in the methods pane beneath. Not all classes have all these extra meta-data fields &#8211; only the relevant extra meta-information fields are displayed. If there are is extra meta-data, then the checkbox is not displayed. This is done in the <i>getMethodsTable</i> function.</p>
<h3 id="methods">Methods or HG hierarchy panel</h3>
<p>The utility&#8217;s main panel displays either a table of methods (functions) for a class object, or a tree hierarchy for an HG handle.</p>
<h4 id="class-methods">Class object methods</h4>
<p>The methods table takes the information from the <i>getObjMethods</i> function, which is an adaptation of Matlab&#8217;s built-in <i><b>methodsview</b></i> function. Part of the adaptation is to hyperlink all class references (used in the methods&#8217; inputs, outputs and meta-data), such that clicking them will open new corresponding <i><b>uiinspect</b></i> windows.<br />
<figure style="width: 468px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Class object methods panel" src="https://undocumentedmatlab.com/images/uiinspect_methods.gif" title="Class object methods panel" width="468" height="219" /><figcaption class="wp-caption-text">Class object methods panel</figcaption></figure><br />
The methods data is displayed within a non-editable Java table (in the <i>getMethodsTable</i> function) that auto-resizes the columns. The table columns are sortable, even sortable on multiple columns by CTRL-clicking (<i><b>methodsview</b></i> allows only simple sorting). This is done using JIDE&#8217;s <a target="_blank" rel="nofollow" href="http://www.jidesoft.com/javadoc/com/jidesoft/grid/TreeTable.html">TreeTable</a> component. The table is placed within a scroll-pane having <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html#scrollbars">automatic scrollbars</a> that only appear as needed.<br />
The table&#8217;s <b>MouseMovedCallback</b> property is set to <i>tbMouseMoved</i>, which updates the mouse cursor (either regular or pointed finger) based on the current mouse position in the table (whether over a hyperlinked cell or not).<br />
The table&#8217;s <b>MousePressedCallback</b> property is set to <i>tbMousePressed</i>, which opens new <i><b>uiinspect</b></i> figure windows for the hyperlinked classes (if any) in the clicked cell.</p>
<h4 id="HG-hierarchy">HG hierarchy tree</h4>
<p>For HG handles, <i>getHandleTree</i> creates a Java tree that displays the hierarchy of HG children (as recursively reported by any HG handle&#8217;s <b>Children</b> property). For convenience, I have chosen to use the built-in component <code>com.mathworks.hg.peer.UITreePeer</code> that underlies the built-in <a target="_blank" href="/articles/uitree/"><i><b>uitree</b></i></a> function. For performance reasons, the tree is not fully evaluated: the inspected handle&#8217;s <b>Parent</b> is set as the tree&#8217;s <b>Root</b>. The root node is expanded to get all the parent&#8217;s <b>Children</b> (i.e., the inspected handle&#8217;s siblings), and then the inspected handle&#8217;s tree node is again expanded to display its direct descendents.<br />
<figure style="width: 283px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Normal dynamic HG handle tooltip" src="https://undocumentedmatlab.com/images/uiinspect_HG_tooltip1.gif" title="Normal dynamic HG handle tooltip" width="283" height="115" /><figcaption class="wp-caption-text">Normal dynamic HG handle tooltip</figcaption></figure><br />
A <b>MouseMovedCallback</b> is set on the tree to process mouse hover events in the <i>treeMouseMovedCallback</i> function. This function updates the tree tooltip dynamically, in the sense that it presents a different tooltip for different handles (tree nodes).<br />
Invalid HG handles (this can happen if the HG handle was deleted since the time that <i><b>uiinspect</b></i> generated the tree) are displayed with a special warning message.<br />
<figure style="width: 350px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Invalid HG handle tooltip" src="https://undocumentedmatlab.com/images/uiinspect_HG_tooltip2.gif" title="Invalid HG handle tooltip" width="350" height="44" /><figcaption class="wp-caption-text">Invalid HG handle tooltip</figcaption></figure><br />
This dynamic tree behavior is achieved by storing the relevant handle information in the <b>UserData</b> of the different tree nodes. Unfortunately, starting in R2012a, Matlab has made a change in the internal support of Java objects, and the <b>UserData</b> property is no longer available. Such a case is detected and the data is stored in the tree nodes&#8217; <b>ApplicationData</b> property instead (using <i><b>setappdata</b>(node,&#8217;userdata&#8217;,&#8230;)</i> ).<br />
<figure style="width: 630px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Dynamic context (right-click) menu" src="https://undocumentedmatlab.com/images/uiinspect3.gif" title="Dynamic context (right-click) menu" width="630" height="488" /><figcaption class="wp-caption-text">Dynamic context (right-click) menu</figcaption></figure><br />
A <b>MousePressedCallback</b> is set on the tree to process context (right-click) events in the <i>treeMousePressedCallback</i> function. The context-menu is also dynamic, in the sense that it presents a different context menu for different handles (tree nodes), again based on their user-data.<br />
Left-clicking a node is not processed by <i>treeMousePressedCallback</i>, but rather by the tree&#8217;s <b>NodeSelectedCallback</b> which is processed in <i>nodeSelected</i>, and by <b>NodeExpandedCallback</b> which is processed by <i>nodeExpanded</i>. <i>nodeSelected</i> reloads <i><b>uiinspect</b></i> for the selected handle; <i>nodeExpanded</i> merely displays the expanded handle&#8217;s children.<br />
Since the &#8216;+&#8217; sign (which triggers <i>nodeExpanded</i>) and the handle icon (which triggers <i>nodeSelected</i>) are so close, we should be careful to click the &#8216;+&#8217;, otherwise the entire <i><b>uiinspect</b></i> window will reload the tree based on the clicked node&#8230; If anyone has a good idea how to solve this dilemma, then I&#8217;m all ears.<br />
Like the methods table, the tree is also placed in a dynamic scroll-pane that displays scrollbars only as needed.</p>
<h3 id="callbacks">Callbacks panel</h3>
<p>The callbacks panel, computed in <i>getCbsData</i> is based on a reflection of the object&#8217;s data as reported by the undocumented built-in <i><b>classhandle</b></i> function. I aggregate all the object&#8217;s events, as well as all the object property names that end with &#8216;Fcn&#8217; or &#8216;Callback&#8217;. This takes care (I hope) of all the different manners by which different kinds of objects raise events that are trappable in Matlab callbacks. Specifically, it takes care of Java/Matlab classes as well as HG handles and COM objects. If anyone thinks that I have forgotten something, please let me know.<br />
The <i>getCbsPane</i> function then displays the callbacks data (callbacks&#8217; property name and value) in a Java table (JIDE <a target="_blank" href="/articles/jide-property-grids/">PropertyTable</a>, JIDE TreeTable, or failing those a simple JTable).<br />
<figure style="width: 551px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Modifiable object callbacks" src="https://undocumentedmatlab.com/images/uiinspect_callbacks.gif" title="Modifiable object callbacks" width="551" height="337" /><figcaption class="wp-caption-text">Modifiable object callbacks</figcaption></figure><br />
The callbacks are automatically grouped by name into logical groups (in <i>getTreeData</i>). For example, all callbacks whose names start with &#8220;Mouse*&#8221; are grouped in the &#8220;Mouse callbacks&#8221; group. The last group is always called &#8220;Other callbacks&#8221; and contains all callbacks for which a matching sibling callback has not been found. The groups are automatically collapsed by default; if only a single group is found then this group is automatically opened (for example, in the case of <i><b>uiinspect</b>(0)</i> ).<br />
The callbacks table&#8217;s toolbar enables displaying the callbacks by groups or sorted alphabetically. It also has &#8220;expand&#8221; and &#8220;collapse&#8221; icons that affect all the groups.<br />
A checkbox next to the table&#8217;s toolbar enables hiding <a target="_blank" href="/articles/uicontrol-callbacks/">standard Java Swing callbacks</a>. This is important when we inspect Java controls and only wish to see its unique callbacks. When using this checkbox, red Java exceptions are sometimes displayed in the Matlab console &#8211; these are harmless and you can safely ignore them (I hope to find a way to prevent them one day).<br />
The table&#8217;s right column displays the callback properties values (if available). This column is editable and we can interactively modify any callback&#8217;s property. As shown, we can enter callback value in either of Matlab&#8217;s supported formats: string, function handle and (for non-COM objects only!) a cell array of function handle and additional data. An error message will be displayed if the callback value is invalid or cannot be set for some reason.<br />
If it is determined that there are no callbacks, then the callbacks panel is automatically minimized, to enable maximum space for the methods panel above it.</p>
<h3 id="inspector">Properties inspector panel</h3>
<p>The properties inspection panel, prepared in <i>getPropsPane</i>, is actually composed of two separate panes: the top pane uses the built-in Matlab component <code>com.mathworks.mlwidgets.inspector.PropertyView</code>, which in turn uses JIDE&#8217;s <a target="_blank" href="/articles/jide-property-grids/">PropertyTable</a>. <code>PropertyView</code> is the same component used by Matlab&#8217;s standard <i><b>inspect</b></i> function (that&#8217;s how I came to know it, if anyone wonders).<br />
<figure style="width: 351px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="uiinspect's property inspector table" src="https://undocumentedmatlab.com/images/PropertyTable.gif" title="uiinspect's property inspector table" width="351" height="216" /><figcaption class="wp-caption-text">uiinspect's property inspector table</figcaption></figure><br />
The benefit of using Matlab&#8217;s <code>PropertyView</code> component rather than JIDE&#8217;s <code>PropertyTable</code> is that <code>PropertyView</code> has the very useful method <i>setObject</i> which I use to point the component at the inspected object, which automatically infers its non-hidden properties and updates the table, saving me a lot of work.<br />
There are two drawbacks of using Matlab&#8217;s <code>PropertyView</code>:</p>
<ul>
<li><code>PropertyView</code> only displays non-hidden properties. One day when I have time, I intent to add the hidden properties to the resulting JIDE <code>PropertyTable</code>. But for now it only shows non-hidden properties.</li>
<li><code>PropertyView</code> causes a Matlab crash on some Matlab releases, in case <i><b>dbstop if error</b></i> is active (this can be replicated using Matlab&#8217;s standard <i><b>inspect</b></i>). I therefore regrettably need to disable this specific <i><b>dbstop</b></i>.</li>
</ul>
<p>I&#8217;ve been meaning to do these two fixes ever since I released <i><b>uiinspect</b></i> back in 2007, but for now that&#8217;s the way it is&#8230;<br />
The properties data is retrieved via the <i>getPropsData</i> function. This function uses the built-in Matlab functions <i><b>meta.class.fromName</b>(className)</i> and <i><b>metaclass</b>(classObject)</i> to get the class handle of Matlab classes (in <i>getMetaClass</i>); similarly, <i>loadClass</i> loads the class definition for a Java class. I inspect these class handles for their contained properties. I then use the <i><b>fieldnames</b></i> function to add static class fields, which are not standard properties (for example, &#8220;RED&#8221; is a static field of the <code>java.awt.Color</code> class).<br />
From the class handle, I retrieve the full definition of each property. This includes meta-data such as whether the property is regular or hidden (undocumented); settable or not; gettable or not; and any additional qualifiers (e.g., Sealed, Dependent, Constant, Abstract, Transient, Default (factory) value).<br />
<figure style="width: 450px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Object properties tooltip" src="https://undocumentedmatlab.com/images/uiinspect_properties1.gif" title="Object properties tooltip" width="450" height="297"/><figcaption class="wp-caption-text">Object properties tooltip</figcaption></figure><br />
We now have a list of all properties and static fields, and this is used to display the entire properties data in the properties panel&#8217;s title (&#8220;Inspectable object properties&#8221;) tooltip. This tooltip, created in <i>updateObjTooltip</i> and <i>getPropsHtml</i>, uses some fancy HTML formatting to display all the object&#8217;s properties and values, color- and font-style-coded to show which of the properties is read-only, hidden, undefined etc.<br />
<figure style="width: 495px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="The 'Other properties' meta-data table" src="https://undocumentedmatlab.com/images/uiinspect_properties2.gif" title="The 'Other properties' meta-data table" width="495" height="317" /><figcaption class="wp-caption-text">The 'Other properties' meta-data table</figcaption></figure><br />
The entire information is also displayed in the properties meta-data pane (&#8220;Other properties&#8221;) beneath JIDE&#8217;s inspector pane. Here we use a simple Java table to display the information in color-coding (gray for read-only properties; blue for static fields; red for irretrievable properties).<br />
Separate checkboxes enable displaying all properties (by default only the properties that are NOT displayed in JIDE&#8217;s inspector table are displayed); and whether or not to display the extra meta-data in the properties table (by default only the property name and current value are displayed).<br />
In some cases (e.g., Dot-Net objects), Matlab&#8217;s inspector does not know how to extract the property-bean information and so the <code>PropertyView</code> inspector is not shown, only the &#8220;other properties&#8221; table.<br />
Both JIDE&#8217;s inspector table and the &#8220;other properties&#8221; table enable the user to modify existing values. Note that in some cases Matlab prevents interactive update of some properties, and in some other cases I have seen Matlab hang when trying to update a few specific properties. But in most cases updating the value does work as expected.<br />
The combination of the inspector table, the meta-data table and the tooltip, enable users to fully understand the accessible properties of the inspected object. Of course, it would have been much better to merge the JIDE inspector table with the hidden properties (=additional rows) and meta-data (=additional columns). But let&#8217;s leave something for the future, shall we?</p>
<h3 id="update">Auto-update mechanism</h3>
<p><figure style="width: 519px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="uiinspect auto-update notice" src="https://undocumentedmatlab.com/images/uiinspect_update.gif" title="uiinspect auto-update notice" width="519" height="190" /><figcaption class="wp-caption-text">uiinspect auto-update notice</figcaption></figure><br />
<i><b>uiinspect</b></i> employs the same auto-update background mechanism used by <i><b>findjobj</b></i> &#8211; after presenting the GUI, the utility silently checks the File Exchange webpage to see whether any newer version of this utility has been uploaded. If so, then a popup notice is presented with the date and description of the latest version. The popup enables users to download the newer version into their Matlab path, or skip. There is also an option to skip the update and not to remind ever again.<br />
I find this background auto-update mechanism quite useful and generic. In fact, I uploaded it as a <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/39993-checkVersion">separate File Exchange utility</a> today, following <a target="_blank" rel="nofollow" href="http://blogs.mathworks.com/pick/2012/12/14/a-conversation-about-managing-file-exchange-downloads/#comment-17358">Brett Shoelson&#8217;s suggestion</a> last month. You can find the underlying code in the <i>checkVersion</i> function.</p>
<h3 id="TODO">TODO</h3>
<ul>
<li>cleanup internal functions, remove duplicates etc.</li>
<li>link property objects to another <i><b>uiinspect</b></i> window for these objects</li>
<li>display object children (&#038; link to them) &#8211; COM/Java</li>
<li>find a way to merge the other-properties table with the inspector table (hidden props + meta-data)</li>
<li>find a way to use the inspector without disabling <i><b>dbstop if error</b></i></li>
<li>Fix: some fields generate a Java Exception from: <code>com.mathworks.mlwidgets.inspector.PropertyRootNode$PropertyListener$1$1.run</code></li>
<li>Fix: using the &#8220;Hide standard callbacks&#8221; checkbox sometimes issues Java Exceptions on the console</li>
<li>Fix: In HG tree view, sometimes the currently-inspected handle is not automatically selected</li>
</ul>
<p>I would be happy if anyone can help with any of these.</p>
<h3 id="conclusion">Conclusion</h3>
<p>I believe that this has been my longest blog post ever; certainly the one that I have labored most over. This correlates well with the <i><b>uiinspect</b></i> utility, which has been one of my most complex tasks. I&#8217;m guessing I must have invested 100-200 man-hours developing and improving it over the years.<br />
I hope you find <i><b>uiinspect</b></i> as useful and as fun as I do. I believe that its source-code is certainly worth reading if you are interested in any advanced Matlab GUI programming, showing how Java GUI components can be combined in Matlab. Go ahead and <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect">download <i><b>uiinspect</b></i></a> from the Matlab file Exchange.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/uiinspect">uiinspect</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/jide-property-grids" rel="bookmark" title="JIDE Property Grids">JIDE Property Grids </a> <small>The JIDE components pre-bundled in Matlab enable creating user-customized property grid tables...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/getting-default-hg-property-values" rel="bookmark" title="Getting default HG property values">Getting default HG property values </a> <small>Matlab has documented how to modify default property values, but not how to get the full list of current defaults. This article explains how to do this. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/findjobj-gui-display-container-hierarchy" rel="bookmark" title="FindJObj GUI &#8211; display container hierarchy">FindJObj GUI &#8211; display container hierarchy </a> <small>The FindJObj utility can be used to present a GUI that displays a Matlab container's internal Java components, properties and callbacks....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/propertiesgui" rel="bookmark" title="propertiesGUI">propertiesGUI </a> <small>propertiesGUI is a utility that presents property-value structs in a convenient table format, useful in Matlab GUIs. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/uiinspect/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Pinning annotations to graphs</title>
		<link>https://undocumentedmatlab.com/articles/pinning-annotations-to-graphs?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=pinning-annotations-to-graphs</link>
					<comments>https://undocumentedmatlab.com/articles/pinning-annotations-to-graphs#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 12 Dec 2012 18:00:51 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[getundoc]]></category>
		<category><![CDATA[Optical illusion]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[scribe]]></category>
		<category><![CDATA[UDD]]></category>
		<category><![CDATA[UIInspect]]></category>
		<category><![CDATA[Undocumented property]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3398</guid>

					<description><![CDATA[<p>Annotation object can be programmatically set at, and pinned-to, plot axes data points. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/pinning-annotations-to-graphs">Pinning annotations to graphs</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/plotly-graphs" rel="bookmark" title="Plotly graphs">Plotly graphs </a> <small>Plotly charts can be created and customized in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jfreechart-graphs-and-gauges" rel="bookmark" title="JFreeChart graphs and gauges">JFreeChart graphs and gauges </a> <small>JFreeChart is an open-source charting library that can easily be integrated in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plotly-graphs-in-ipython-notebook" rel="bookmark" title="Plotly graphs in IPython Notebook">Plotly graphs in IPython Notebook </a> <small>Plotly graphs can be embedded in an IPython Notebook directly from Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/bug-and-workaround-in-timeseries-plot" rel="bookmark" title="Bug and workaround in timeseries plot">Bug and workaround in timeseries plot </a> <small>Matlab's internal hgconvertunits function has a bug that affects timeseries plots. Luckily there is a simple workaround....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Many Matlab users are aware of Matlab&#8217;s <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/creating_plots/how-to-annotate-graphs.html">annotation functionality</a>, which enables us to assign graphic elements such as arrows, lines, ellipses and text labels to Matlab figures. Matlab has a corresponding built-in function, <i><b>annotation</b></i>, that enables creation of annotation objects. Through the handle returned by <i><b>annotation</b></i> we can customize the annotation&#8217;s appearance (for example, line width/style or text font properties).</p>
<h3 id="limitations">Limitations of Matlab annotations</h3>
<p>Unfortunately, <i><b>annotation</b></i> has several major deficiencies, that are in fact related:<br />
<figure style="width: 406px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="A Matlab text-arrow annotation (unpinned)" src="https://undocumentedmatlab.com/images/Annotation_unpinned_animated.gif" title="A Matlab text-arrow annotation (unpinned)" width="406" height="298" /><figcaption class="wp-caption-text">A Matlab text-arrow annotation (unpinned)</figcaption></figure></p>
<ol>
<li><i><b>annotation</b></i> requires us to specify the annotation&#8217;s position in normalized <u>figure</u> units. Often, we are interested in an annotation on a plot axes that does NOT span the entire figure&#8217;s content area. To correctly convert the position from plot axes data coordinates to figure coordinates requires non-trivial calculations.</li>
<li>The created annotation is NOT pinned to the plot axes by default. This means that the annotation retains its relative position in the figure when the plot is zoomed, panned or rotated. This results in unintelligible and misleading annotations. We can indeed pin the annotation to the graph, but this requires delicate manual interaction (click the Edit Plot toolbar icon, then right-click the relevant annotation end-point, then select &#8220;Pin to Axes&#8221; from context menu). Unfortunately, the annotation handle does not provide a documented way to do this programmatically.</li>
<li>Finally, the annotation objects are only displayed on top of plot axes &#8211; they are obscured by any GUI uicontrols that may happen to be present in the figure.</li>
</ol>
<p>All of these limitations originate from the underlying implementation of annotation objects in Matlab. This is based on a transparent hidden axes that spans the entire figure&#8217;s content area, on which the annotations are being drawn (also called the <i>scribe layer</i>). The annotations may appear to be connected to the plot axes, but this is merely a visual illusion. In fact, they are located in a separate axes layer. For this reason, <i><b>annotation</b></i> requires figure position &#8211; in fact, the annotation has no information about the axes beneath it. Since plot axes are always obscured by uicontrols, so too is the annotation layer.<br />
Matlab&#8217;s implementation of annotation is an attempt to replicate Java&#8217;s standard <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html">glass-pane mechanism</a>. But whereas the Java glass-pane is a true transparent layer, on top of all other window components (<a target="_blank" rel="nofollow" href="http://www.codebeach.com/2008/03/introduction-to-glass-panes-in-swing.html">examples</a>), Matlab&#8217;s implementation only works for axes.<br />
Oh well, it&#8217;s better than nothing, I guess. But still, it would be nice if we could specify the annotation in graph (plot axes) data units, and have it pinned automatically without requiring manual user interaction.<br />
<span id="more-3398"></span></p>
<h3 id="Debugging">Debugging the problem</h3>
<p>The obvious first place to start debugging this issue is to go to the annotation handle&#8217;s context-menu (accessible via the <b>UIContextMenu</b> property), drill down to the &#8220;Pin&#8221; menu item and take a look at its callback. We could then use the <i><b><a target="_blank" href="/articles/hgfeval/">hgfeval</a></b></i> function to execute this callback programmatically. Unfortunately, this does not work well, because the context-menu is empty when the annotation is first created. A context-menu is only assigned to the annotation after the Edit Plot toolbar button and then the annotation object are clicked.<br />
Being too lazy in nature to debug this all the way through, I opted for an easier route: I started the Profiler just prior to clicking the context-menu&#8217;s &#8220;Pin to Axes&#8221;, and stopped it immediately afterwards. This showed me the code path (beneath <i>%matlabroot%/toolbox/matlab/scribe/</i>), and placing breakpoints in key code lines enabled me to debug the process step-by-step. This in turn enabled me to take the essence of the pinning code and implement it in my stand-alone application code.<br />
Believe me when I say that the scribe code is complex (anyone say convoluted?). So I&#8217;ll spare you the gruesome details and skip right to the chase.</p>
<h3 id="solution">The solution</h3>
<h5 id="positioning">Positioning the annotation in axes data units</h5>
<p>The first step is to ensure that the initial annotation position is within the figure bounds. Otherwise, the <i><b>annotation</b></i> function will shout. Note that it is ok to move the annotation outside the figure bounds later on (via panning/zooming) &#8211; it is only the initial annotation creation that must be within the figure bounds (i.e., between 0.0-1.0 in normalized X and Y units):</p>
<pre lang='matlab'>
% Prepare the annotation's X position
% Note: we need 2 X values: one for the annotation's head, another for the tail
x = [xValue, xValue];
xlim = get(hAxes,'XLim');
% Prepare the annotation's Y position
% Note: we need 2 Y values: one for the annotation's head, another for the tail
% Note: we use a static Y position here, spanning the center of the axes.
% ^^^^  We could have used some other Y data value for this
yLim = get(hAxes,'YLim');
y = yLim(1) + 0*sum(yLim) + [0.1,0]*diff(ylim);  % TODO: handle reverse, log Y axes
% Ensure that the annotation fits in the window by enlarging
% the axes limits as required
if xValue < xlim(1) || xValue > xlim(2)
    hold(hAxes,'on');
    plot(hAxes,xValue,y(2),'-w');
    drawnow;
    % YLim may have changed, so recalculate y
    yLim = get(hAxes,'YLim');
    y = yLim(1) + 0*sum(yLim) + [0.1,0]*diff(ylim);  % TODO: handle reverse, log Y-axes
end
</pre>
<p>Next, we convert our plot data units, in order to get the annotation&#8217;s requested position in the expected figure units. For this we use <i>%matlabroot%/toolbox/matlab/scribe/@scribe/@scribepin/topixels.m</i>. This is an internal method of the <code>scribepin</code> UDD class, so in order to use it we need to create a dummy <code>scribepin</code> object. <i>topixels</i> then converts the dummy object&#8217;s position from axes data units to pixel units. We then use the undocumented <i><b><a target="_blank" href="/articles/bug-and-workaround-in-timeseries-plot/">hgconvertunits</a></b></i> function to convert from pixel units into normalized figure units:</p>
<pre lang='matlab'>
% Convert axes data position to figure normalized position
% uses %matlabroot%/toolbox/matlab/scribe/@scribe/@scribepin/topixels.m
scribepin = scribe.scribepin('parent',hAxes,'DataAxes',hAxes,'DataPosition',[x;y;[0,0]]');
figPixelPos = scribepin.topixels;
hFig = ancestor(hAxes,'figure');
figPos = getpixelposition(hFig);
figPixelPos(:,2) = figPos(4) - figPixelPos([2,1],2);
figNormPos = hgconvertunits(hFig,[figPixelPos(1,1:2),diff(figPixelPos)],'pixels','norm',hFig);
annotationX = figNormPos([1,1]);
annotationY = figNormPos([2,2]) + figNormPos(4)*[1,0];
</pre>
<h5 id="pinning">Pinning the annotation to the axes data</h5>
<p>Finally, we use the annotation handle&#8217;s <i>pinAtAffordance()</i> method and set the <b>Pin.DataPosition</b> property to the requested X,Y values (we need to do both of these, otherwise the annotation will jump around when we zoom/pan):<br />
<center><figure style="width: 406px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="A Matlab text-arrow annotation (pinned)" src="https://undocumentedmatlab.com/images/Annotation_pinned_animated.gif" title="A Matlab text-arrow annotation (pinned)" width="406" height="298" /><figcaption class="wp-caption-text">A Matlab text-arrow annotation (pinned)</figcaption></figure></center></p>
<pre lang='matlab'>
% Ensure that the annotation is within the axes bounds, then display it
if any([annotationX,annotationY] < 0) || any([annotationX,annotationY] > 1)
    % Annotation position is outside axes boundaries, so bail out without drawing
    hAnnotation = handle([]);
elseif ~isempty(annotationObj)
    % Create a text-arrow annotation with the requested string at the requested position
    hAnnotation = handle(annotation('textarrow', annotationX, annotationY, ...
                                    'String',annotationStr, 'TextColor','b', 'Tag','annotation'));
    % Example for setting annotation properties
    hAnnotation.TextEdgeColor = [.8,.8,.8];
    % Pin the annotation object to the required axes position
    % Note: some of the following could fail in certain cases - never mind
    try
        hAnnotation.pinAtAffordance(1);
        hAnnotation.pinAtAffordance(2);
        hAnnotation.Pin(1).DataPosition = [xValue, y(1), 0];
        hAnnotation.Pin(2).DataPosition = [xValue, y(2), 0];
    catch
        % never mind - ignore (no error)
    end
end
</pre>
<p>p.s. Notice that all this relies on pure Matlab code (i.e., no mention of the dreaded J-word&#8230;). In fact, practically the entire scribe code is available in m-file format in the base Matlab installation. Masochistic readers may find many hours of pleasure sifting through the scribe code functionality for interesting nuggets such as the one above. If you ever find any interesting items, please drop me an email, or post a comment below.</p>
<h3 id="undocumented">Undocumented annotation properties</h3>
<p>Annotation objects have a <u>huge</u> number of undocumented properties. In fact, they have more undocumented properties than documented ones. You can see this using my <i><b><a target="_blank" href="/articles/uiinspect/">uiinspect</a></b></i> or <i><b><a target="_blank" href="/articles/getundoc-get-undocumented-object-properties/">getundoc</a></b></i> utilities. Here is the list for a simple text-arrow annotation, such as the one that we used above:</p>
<pre lang='matlab'>
>> getundoc(hAnnotation)
ans =
              ALimInclude: 'on'
                   Afsize: 6
          ApplicationData: [1x1 struct]
                 Behavior: [1x1 struct]
              CLimInclude: 'on'
               ColorProps: {5x1 cell}
     EdgeColorDescription: 'Color'
        EdgeColorProperty: 'Color'
                  Editing: 'off'
                EraseMode: 'normal'
     FaceColorDescription: 'Head Color'
        FaceColorProperty: 'HeadColor'
             FigureResize: 0
            HeadBackDepth: 0.35
                HeadColor: [0 0 0]
            HeadColorMode: 'auto'
            HeadEdgeColor: [0 0 0]
            HeadFaceAlpha: 1
            HeadFaceColor: [0 0 0]
               HeadHandle: [1x1 patch]
         HeadHypocycloidN: 3
            HeadLineStyle: '-'
            HeadLineWidth: 0.5
               HeadRosePQ: 2
                 HeadSize: 10
             HelpTopicKey: ''
          IncludeRenderer: 'on'
                 MoveMode: 'mouseover'
                    NormX: [0.2 0.4]
                    NormY: [0.5 0.7]
                      Pin: [0x1 double]
                   PinAff: [1 2]
           PinContextMenu: [2x1 uimenu]
                PinExists: [0 0]
              PixelBounds: [0 0 0 0]
        PropertyListeners: [8x1 handle.listener]
        ScribeContextMenu: [9x1 uimenu]
                 Selected: 'off'
             Serializable: 'on'
                ShapeType: 'textarrow'
                    Srect: [2x1 line]
           StoredPosition: []
                TailColor: [0 0 0]
               TailHandle: [1x1 line]
            TailLineStyle: '-'
            TailLineWidth: 0.5
     TextColorDescription: 'Text Color'
            TextColorMode: 'auto'
        TextColorProperty: 'TextColor'
        TextEdgeColorMode: 'manual'
            TextEraseMode: 'normal'
               TextHandle: [1x1 text]
         UpdateInProgress: 0
    VerticalAlignmentMode: 'auto'
              XLimInclude: 'on'
              YLimInclude: 'on'
              ZLimInclude: 'on'
</pre>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/pinning-annotations-to-graphs">Pinning annotations to graphs</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/plotly-graphs" rel="bookmark" title="Plotly graphs">Plotly graphs </a> <small>Plotly charts can be created and customized in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/jfreechart-graphs-and-gauges" rel="bookmark" title="JFreeChart graphs and gauges">JFreeChart graphs and gauges </a> <small>JFreeChart is an open-source charting library that can easily be integrated in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plotly-graphs-in-ipython-notebook" rel="bookmark" title="Plotly graphs in IPython Notebook">Plotly graphs in IPython Notebook </a> <small>Plotly graphs can be embedded in an IPython Notebook directly from Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/bug-and-workaround-in-timeseries-plot" rel="bookmark" title="Bug and workaround in timeseries plot">Bug and workaround in timeseries plot </a> <small>Matlab's internal hgconvertunits function has a bug that affects timeseries plots. Luckily there is a simple workaround....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/pinning-annotations-to-graphs/feed</wfw:commentRss>
			<slash:comments>13</slash:comments>
		
		
			</item>
	</channel>
</rss>
