<?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>Callbacks &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/callbacks/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Fri, 13 Dec 2024 11:14:57 +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>Matlab toolstrip – part 4 (control customization)</title>
		<link>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-toolstrip-part-4-control-customization</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 30 Dec 2018 16:00:00 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8110</guid>

					<description><![CDATA[<p>Matlab toolstrip components (controls) can be customized in various ways, including user-defined callbacks. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization">Matlab toolstrip – part 4 (control customization)</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/matlab-toolstrip-part-3-basic-customization" rel="bookmark" title="Matlab toolstrip – part 3 (basic customization)">Matlab toolstrip – part 3 (basic customization) </a> <small>Matlab toolstrips can be created and customized in a variety of ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls" rel="bookmark" title="Matlab toolstrip – part 6 (complex controls)">Matlab toolstrip – part 6 (complex controls) </a> <small>Multiple types of customizable controls can be added to Matlab toolstrips...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls" rel="bookmark" title="Matlab toolstrip – part 7 (selection controls)">Matlab toolstrip – part 7 (selection controls) </a> <small>Matlab toolstrips can contain a wide variety of selection controls: popups, combo-boxes, and galleries. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In a <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization" target="_blank">previous post</a> I showed how we can create custom Matlab app toolstrips. Toolstrips can be a bit complex to develop so I’m trying to proceed slowly, with each post in the miniseries building on the previous posts. I encourage you to review the earlier posts in <a href="https://undocumentedmatlab.com/articles/tag/toolstrip" target="_blank">the Toolstrip miniseries</a> before reading this post. In today&#8217;s post we continue the discussion of the toolstrip created in the previous post:<br />
<center><figure style="width: 440px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_basic_controls.png" alt="Toolstrip example (basic controls)" title="Toolstrip example (basic controls)" width="100%" style="max-width:553px; margin:0" /><figcaption class="wp-caption-text">Toolstrip example (basic controls)</figcaption></figure></center><br />
Today&#8217;s post will show how to attach user-defined functionality to toolstrip components, as well as some additional customizations. At the end of today&#8217;s article, you should be able to create a fully-functional custom Matlab toolstrip. <span id="more-8110"></span> Today&#8217;s post will remain within the confines of a Matlab &#8220;app&#8221;, i.e. a tool-group that displays docked figures. Future posts will discuss lower-level toolstrip mechanisms, that enable advanced customizations as well as integration in legacy (Java-based, even GUIDE-created) Matlab figures.</p>
<h3 id="callbacks">Control callbacks</h3>
<p>Controls are useless without settable callbacks that affect the program state based on user interactions. There are two different mechanisms for setting callbacks for Matlab toolstrip controls. Refer to the example in the <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization#example" target="_blank">previous post</a>:</p>
<ol>
<li>Setting the control&#8217;s callback property or properties &#8211; the property names differ across components (no, for some reason it&#8217;s never as simple as <b>Callback</b> in standard uicontrols). For example, the main action callback for push-buttons is <b>ButtonPushedFcn</b>, for toggle-buttons and checkboxes it&#8217;s <b>ValueChangedFcn</b> and for listboxes it&#8217;s <b></b>. Setting the callback is relatively easy:
<pre lang="matlab">
hColorbar.ValueChangedFcn = @toggleColorbar;
function toggleColorbar(hAction,hEventData)
    if hAction.Selected
        colorbar;
    else
        colorbar('off');
    end
end
</pre>
<p>The <code>hAction</code> object that is passed to the callback function as the first input arg contains various fields of interest, but for some reason the most important object property (<b>Value</b>) is renamed as the <b>Selected</b> property (most confusing). Also, a back-reference to the originating control (<code>hColorbar</code> in this example), which is important for many callbacks, is also missing (and no &#8211; I couldn&#8217;t find it in the hidden properties either):</p>
<pre lang="matlab">
>> hAction
hAction =
  Action with properties:
            Description: 'Toggle colorbar display'
                Enabled: 1
               Shortcut: ''
               Selected: 1
        QuickAccessIcon: []
    SelectionChangedFcn: @toggleColorbar
                   Text: 'Colorbar'
        IsInQuickAccess: 0
            ButtonGroup: []
                   Icon: [1×1 matlab.ui.internal.toolstrip.Icon]
>> hEventData
hEventData =
  ToolstripEventData with properties:
    EventData: [1×1 struct]
       Source: [0×0 handle]
    EventName: ''
>> hEventData.EventData
ans =
  struct with fields:
    Property: 'Value'
    NewValue: 1
    OldValue: 0
</pre>
<p>Note that <code>hEventData.Source</code> is an empty handle for some unknown reason.<br />
The bottom line is that to reference the button state using this callback mechanism we need to either:</p>
<ol>
<li>Access <code>hAction</code>&#8216;s <b>Selected</b> property which stands-in for the originating control&#8217;s <b>Value</b> property (this is what I have shown in the short code snippet above)</li>
<li>Access <code>hEventData.EventData</code> and use its reported Property, NewValue and OldValue fields</li>
<li>Pass the originating control handle as an extra (3rd) input arg to the callback function, and then access it from within the callback. For example:
<pre lang="matlab">
hColorbar.ValueChangedFcn = {@toggleColorbar, hColorbar};
function toggleColorbar(hAction,hEventData,hButton)
    if hButton.Value %hAction.Selected
        colorbar;
    else
        colorbar('off');
    end
end
</pre>
</ol>
</li>
<li>As an alternative, we can use the <i><b>addlistener</b></i> function to attach a callback to control events. Practically all toolstrip components expose public events that can be listened-to using this mechanism. In most cases the control&#8217;s callback property name(s) closely follow the corresponding events. For example, for buttons we have the <b>ValueChanged</b> event that corresponds to the <b>ValueChangedFcn</b> property. We can use listeners as follows:
<pre lang="matlab">
hCheckbox.addlistener('ValueChanged',@toggleLogY);
function toggleLogY(hCheckbox,hEventData)
    if hCheckbox.Value, type = 'log'; else, type = 'linear'; end
    set(gca, 'XScale',type, 'YScale',type, 'ZScale',type);
end
</pre>
<p>Note that when we use the <i><b>addlistener</b></i> mechanism to attach callbacks, we don&#8217;t need any of the tricks above &#8211; we get the originating control handle as the callback function&#8217;s first input arg, and we can access it directly.<br />
Unfortunately, we cannot pass extra args to the callback that we specify using <i><b>addlistener</b></i> (this seems like a trivial and natural thing to have, for MathWorks&#8217; attention&#8230;). In other words, <i><b>addlistener</b></i> only accepts a function handle as callback, not a cell array. To bypass this limitation in uicontrols, we typically add the extra parameters to the control&#8217;s <b>UserData</b> or <b>ApplicationData</b> properties (the latter via the <i><b>setappdata</b></i> function). But alas &#8211; toolstrip components have neither of these properties, nor can we add them in runtime (<a href="https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects" target="_blank">as with for other GUI controls</a>). So we need to find some other way to pass these extra values, such as using global variables, or making the callback function nested so that it could access the parent function&#8217;s workspace.
</li>
</ol>
<h3 id="props">Additional component properties</h3>
<p>Component text labels, where relevant, can be set using the component&#8217;s <b>Text</b> property, and the tooltip can be set via the <b>Description</b> property. As I noted in my previous post, I believe that this is an unfortunate choice of property names. In addition, components have control-specific properties such as <b>Value</b> (checkboxes and toggle buttons). These properties can generally be modified in runtime, in order to reflect the program state. For example, we can disable/enable controls, and modify their label, tooltip and state depending on the control&#8217;s new state and the program state in general.<br />
The component icon can be set via the <b>Icon</b> property, where available (for example, buttons have an icon, but checkboxes do not). There are several different ways in which we can set this <b>Icon</b>. I will discuss this in detail in the following post; in the meantime you can review the usage examples in the previous post.<br />
There are a couple of additional hidden component properties that seem promising, most notably <b>Shortcut</b> and <b>Mnemonic</b> (the latter (Mnemonic) is also available in <code>Section</code> and <code>Tab</code>, not just in components). Unfortunately, at least as of R2018b these properties do not seem to be connected yet to any functionality. In the future, I would expect them to correspond to keyboard shortcuts and underlined mnemonic characters, as these functionalities behave in standard menu items.</p>
<h3 id="Java">Accessing the underlying Java control</h3>
<p>As long as we&#8217;re not displaying the toolstrip on a browser page (i.e., inside a uifigure or Matlab Online), the toolstrip is basically composed of Java Swing components from the <code>com.mathworks.toolstrip.components</code> package (such as <code>TSButton</code> or <code>TSCheckBox</code>). I will discuss these Java classes and their customizations in a later post, but for now I just wish to show how to access the underlying Java component of any Matlab MCOS control. This can be done using a central registry of toolstrip components (so-called &#8220;widgets&#8221;), which is accessible via the <code>ToolGroup</code>&#8216;s hidden <b>ToolstripSwingService</b> property, and then via each component&#8217;s hidden widget Id. For example:</p>
<pre lang="matlab">
>> widgetRegistry = hToolGroup.ToolstripSwingService.Registry;
>> jButton = widgetRegistry.getWidgetById(hButton.getId)  % get the hButton's underlying Java control
ans =
com.mathworks.toolstrip.components.TSToggleButton[,"Colorbar",layout<>,NORMAL]
</pre>
<p>We can now apply a wide variety of Java-based customizations to the retrieved <code>jButton</code>, as I have shown in many other articles on this website over the past decade.<br />
Another way to access the toolstrip Java component hierarchy is via <code>hToolGroup.Peer.get(tabIndex).getComponent</code>. This returns the top-level Java control representing the tab whose index in <code>tabIndex</code> (0=left-most tab):</p>
<pre lang="matlab">
>> jToolGroup = hToolGroup.Peer;  % or: =hToolGroup.ToolstripSwingService.SwingToolGroup;
>> jDataTab = jToolGroup.get(0).getComponent;  % Get tab #0 (first tab: "Data")
>> jDataTab.list   % The following is abridged for brevity
com.mathworks.toolstrip.impl.ToolstripTabContentPanel[tab0069230a-52b0-4973-b025-2171cd96301b,0,0,831x93,...]
 SectionWrapper(section54fb084c-934d-4d31-9468-7e4d66cd85e5)
  com.mathworks.toolstrip.impl.ToolstripSectionComponentWithHeader[,0,0,241x92,...]
   com.mathworks.toolstrip.components.TSPanel[section54fb084c-934d-4d31-9468-7e4d66cd85e5,,layout<horizontal>,NORMAL]
    TSColumn -> layout<> :
     com.mathworks.toolstrip.components.TSButton[,"Refresh all",layout<>,NORMAL]
    TSColumn -> layout<> :
     com.mathworks.toolstrip.components.TSButton[,"Refresh X,Y",layout<>,NORMAL]
     com.mathworks.toolstrip.components.TSButton[,"Refresh Y,Z",layout<>,NORMAL]
    TSColumn -> layout<> :
     com.mathworks.toolstrip.components.TSButton[,"Refresh X",layout<>,NORMAL]
     com.mathworks.toolstrip.components.TSButton[,"Refresh Y",layout<>,NORMAL]
     com.mathworks.toolstrip.components.TSButton[,"Refresh Z",layout<>,NORMAL]
 SectionWrapper(sectionebd8ab95-fd33-4a3d-8f24-152589713994)
  com.mathworks.toolstrip.impl.ToolstripSectionComponentWithHeader[,0,0,159x92,...]
   com.mathworks.toolstrip.components.TSPanel[sectionebd8ab95-fd33-4a3d-8f24-152589713994,,layout<horizontal>,NORMAL]
    TSColumn -> layout<> :
     com.mathworks.toolstrip.components.TSCheckBox[,"Axes borders",layout<>,NORMAL]
     com.mathworks.toolstrip.components.TSCheckBox[,"Log scaling",layout<>,NORMAL]
     com.mathworks.toolstrip.components.TSCheckBox[,"Inverted Y",layout<>,NORMAL]
 SectionWrapper(section01995bfd-61de-490f-aa22-de50bae1af75)
  com.mathworks.toolstrip.impl.ToolstripSectionComponentWithHeader[,0,0,125x92,...]
   com.mathworks.toolstrip.components.TSPanel[section01995bfd-61de-490f-aa22-de50bae1af75,,layout<horizontal>,NORMAL]
    TSColumn -> layout<> :
     com.mathworks.toolstrip.components.TSToggleButton[,"Legend",layout<>,NORMAL]
    TSColumn -> layout<> :
     com.mathworks.toolstrip.components.TSLabel[null," ",layout<>,NORMAL]
     com.mathworks.toolstrip.components.TSToggleButton[,"Colorbar",layout<>,NORMAL]
     com.mathworks.toolstrip.components.TSLabel[null," ",layout<>,NORMAL]
 com.mathworks.mwswing.MJButton[toolstrip.header.collapseButton,808,70,20x20,...]
</pre>
<h3 id="roadmap">Toolstrip miniseries roadmap</h3>
<p>The next post will discuss icons, for both toolstrip controls as well as the ToolGroup app window.<br />
I plan to discuss complex components in subsequent posts. Such components include button-group, drop-down, listbox, split-button, slider, popup form, gallery etc.<br />
Following that, my plan is to discuss toolstrip collapsibility, the ToolPack framework, docking layout, DataBrowser panel, QAB (Quick Access Bar), underlying Java controls, and adding toolstrips to figures &#8211; not necessarily in this order.<br />
Have I already mentioned that Matlab toolstrips can be a bit complex?<br />
If you would like me to assist you in building a custom toolstrip or GUI for your Matlab program, <a href="https://undocumentedmatlab.com/consulting" target="_blank">please let me know</a>.<br />
Happy New Year, everyone!</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization">Matlab toolstrip – part 4 (control customization)</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/matlab-toolstrip-part-3-basic-customization" rel="bookmark" title="Matlab toolstrip – part 3 (basic customization)">Matlab toolstrip – part 3 (basic customization) </a> <small>Matlab toolstrips can be created and customized in a variety of ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls" rel="bookmark" title="Matlab toolstrip – part 6 (complex controls)">Matlab toolstrip – part 6 (complex controls) </a> <small>Multiple types of customizable controls can be added to Matlab toolstrips...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls" rel="bookmark" title="Matlab toolstrip – part 7 (selection controls)">Matlab toolstrip – part 7 (selection controls) </a> <small>Matlab toolstrips can contain a wide variety of selection controls: popups, combo-boxes, and galleries. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Matlab GUI training seminars &#8211; Zurich, 29-30 August 2017</title>
		<link>https://undocumentedmatlab.com/articles/matlab-gui-training-seminars-zurich-29-30-august-2017?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-gui-training-seminars-zurich-29-30-august-2017</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-gui-training-seminars-zurich-29-30-august-2017#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Fri, 04 Aug 2017 09:37:52 +0000</pubDate>
				<category><![CDATA[Public presentation]]></category>
		<category><![CDATA[AppDesigner]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[GUIDE]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JIDE]]></category>
		<category><![CDATA[training]]></category>
		<category><![CDATA[uicontrol]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6992</guid>

					<description><![CDATA[<p>Advanced Matlab training courses on Matlab User Interfaces (GUI) will be presented in Zurich Switzerland on 29-30 August, 2017</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-gui-training-seminars-zurich-29-30-august-2017">Matlab GUI training seminars &#8211; Zurich, 29-30 August 2017</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/matlab-expo-bern-22-june-2017" rel="bookmark" title="Matlab Expo &#8211; Bern, 22 June 2017">Matlab Expo &#8211; Bern, 22 June 2017 </a> <small>I will be speaking about easy-to-use Matlab tricks at the upcoming Matlab Expo in Bern, Switzerland on June 22, 2017. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/findjobj-find-underlying-java-object" rel="bookmark" title="FindJObj &#8211; find a Matlab component&#039;s underlying Java object">FindJObj &#8211; find a Matlab component&#039;s underlying Java object </a> <small>The FindJObj utility can be used to access and display the internal components of Matlab controls and containers. This article explains its uses and inner mechanism....</small></li>
<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/training" rel="bookmark" title="New training courses">New training courses </a> <small>I am now offering a new service of professional Matlab training, at your location. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><span class="alignright"><img fetchpriority="high" decoding="async" alt="Advanced Matlab training, Zurich 29-30 August 2017" src="https://undocumentedmatlab.com/images/20140520_153734a_500x321.jpg" title="Advanced Matlab training, Zurich 29-30 August 2017" width="400" height="257"/></span><br />
Advanced Matlab training courses/seminars will be presented by me (Yair) in Zürich, Switzerland on 29-30 August, 2017:</p>
<ul>
<li>August 29 (full day) &#8211; <b>Interactive Matlab GUI</b></li>
<p> <!-- - US$399 (CHF 390.-) ($100 discount if paid by July 31) --></p>
<li>August 30 (full day) &#8211; <b>Advanced Matlab GUI</b></li>
<p> <!-- - US$399 (CHF 390.-) ($100 discount if paid by July 31) --><br />
	<!-- li>Enroll to both courses (2 full days) for a total price of US$699 (CHF 680.-)</li --> <!-- ($150 extra discount if paid by July 31) -->
</ul>
<p><!-- b>Both seminars are confirmed</b>: they do not depend on a minimal number of participants. But there is a limit on the total number of participants, so the sooner you enroll, the more likely you are to get a seat. --><br />
The seminars are targeted at Matlab users who wish to improve their program&#8217;s usability and professional appearance. Basic familiarity with the Matlab environment and coding/programming is assumed. The courses will present a mix of both documented and undocumented aspects, which is not available anywhere else. The curriculum is listed below.<br />
This is a unique opportunity to enhance your Matlab coding skills and improve your program&#8217;s usability in a couple of days<!-- , at a very affordable cost -->.<br />
If you are interested in either or both of these seminars, please <a href="mailto:%20altmany%20@gmail.com?subject=Matlab%20training%20Zurich&amp;body=Hi%20Yair,%20&amp;cc=;&amp;bcc=" rel="nofollow" target="_blank" onclick="var n='altmany'; var d='gmail.com'; window.open('mailto:'+n+'@'+d+'?subject=Matlab training Zurich&amp;body=Hi Yair, '); return false;">Email me</a> (altmany at gmail dot com).<br />
I can also schedule a dedicated visit to your location, for onsite Matlab training customized to your organization&#8217;s specific needs. Additional information can be found on my <a target="_blank" href="/training/">Training page</a>.<br />
Around the time of the training, I will be traveling to various locations around Switzerland. <!-- in Geneva (Aug 22-27), Bern (Aug 27-28), Zürich (Aug 28-30), and Basel (Aug 30 - Sep 3) --> If you wish to meet me in person to discuss how I could bring value to your project, then please email me (altmany at gmail):</p>
<ul>
<li>Geneva: Aug 22 &#8211; 27</li>
<li>Bern: Aug 27 &#8211; 28</li>
<li>Zürich: Aug 28 &#8211; 30</li>
<li>Stuttgart: Aug 30 &#8211; 31</li>
<li>Basel: Sep 1 &#8211; 3</li>
</ul>
<p><img decoding="async" src="https://undocumentedmatlab.com/images/email-icon.png" width="32" height="22" alt="" style="vertical-align:middle;border:0"/>&nbsp;<a href="mailto: altmany @gmail.com?subject=Matlab consulting/training&#038;body=Hi Yair, &#038;cc=;&#038;bcc=" rel="nofollow" target="_blank" onclick="var n='altmany'; var d='gmail.com'; window.open('mailto:'+n+'@'+d+'?subject=Matlab consulting/training&#038;body=Hi Yair, '); return false;">Email me</a><br />
<span id="more-6992"></span></p>
<hr/>
<h3 id="GUI">Interactive Matlab GUI &#8211; 29 August, 2017</h3>
<ol>
<li>Introduction to Matlab Graphical User Interfaces (GUI)
<ul>
<li>Design principles and best practices</li>
<li>Matlab GUI alternatives</li>
<li>Typical evolution of Matlab GUI developers</li>
</ul>
</li>
<li>GUIDE – MATLAB&#8217;s GUI Design Editor
<ul>
<li>Using GUIDE to design a custom GUI</li>
<li>Available built-in MATLAB uicontrols</li>
<li>Customizing uicontrols</li>
<li>Important figure and uicontrol properties</li>
<li>GUIDE utility windows</li>
<li>The GUIDE-generated file-duo</li>
</ul>
</li>
<li>Customizing GUI appearance and behavior
<ul>
<li>Programmatic GUI creation and control</li>
<li>GUIDE vs. m-programming</li>
<li>Attaching callback functionality to GUI components</li>
<li>Sharing data between GUI components</li>
<li>The handles data struct</li>
<li>Using handle visibility</li>
<li>Position, size and units</li>
<li>Formatting GUI using HTML</li>
</ul>
</li>
<li>Uitable
<ul>
<li>Displaying data in a MATLAB GUI uitable</li>
<li>Controlling column data type</li>
<li>Customizing uitable appearance</li>
<li>Reading uitable data</li>
<li>Uitable callbacks</li>
<li>Additional customizations using Java</li>
</ul>
</li>
<li>Matlab&#8217;s new App Designer and web-based GUI
<ul>
<li>App Designer environment, widgets and code</li>
<li>The web-based future of Matlab GUI and assumed roadmap</li>
<li>App Designer vs. GUIDE – pros and cons comparison</li>
</ul>
</li>
<li>Performance and interactivity considerations
<ul>
<li>Speeding up the initial GUI generation</li>
<li>Improving GUI responsiveness</li>
<li>Actual vs. perceived performance</li>
<li>Continuous interface feedback</li>
<li>Avoiding common performance pitfalls</li>
<li>Tradeoff considerations</li>
</ul>
</li>
</ol>
<p><!-- Throughout the day, a sample data-structure container class will be developed and presented in phases, illustrating the points discussed in the presentation, along with suggestions and discussion on design alternatives, programming quality, efficiency, robustness, maintainability, and performance. In other words, the seminar will include not just a formal presentation of the material but also a live annotated development of a real-world Matlab class that illustrates the presented topics. --><br />
At the end of this seminar, you will have learned how to:</p>
<ul>
<li>apply GUI design principles in Matlab</li>
<li>create simple Matlab GUIs</li>
<li>manipulate and customize graphs, images and GUI components</li>
<li>display Matlab data in a variety of GUI manners, including data tables</li>
<li>decide between using GUIDE, App Designer and/or programmatic GUI</li>
<li>understand tradeoffs in design and run-time performance</li>
<li>comprehend performance implications, to improve GUI speed and responsiveness</li>
</ul>
<hr/>
<h3 id="AMG">Advanced Matlab GUI &#8211; 30 August, 2017</h3>
<ol>
<li>Advanced topics in Matlab GUI
<ul>
<li>GUI callback interrupts and re-entrancy</li>
<li>GUI units and resizing</li>
<li>Advanced HTML formatting</li>
<li>Using hidden (undocumented) properties</li>
<li>Listening to action and property-change events</li>
<li>Uitab, uitree, uiundo and other uitools</li>
</ul>
</li>
<li>Customizing the figure window
<ul>
<li>Creating and customizing the figure&#8217;s main menu</li>
<li>Creating and using context menus</li>
<li>Creating and customizing figure toolbars</li>
</ul>
</li>
<li>Using Java with Matlab GUI
<ul>
<li>Matlab and Java Swing</li>
<li>Integrating Java controls in Matlab GUI</li>
<li>Handling Java events as Matlab callbacks</li>
<li>Integrating built-in Matlab controls/widgets</li>
<li>Integrating JIDE&#8217;s advanced features and professional controls</li>
<li>Integrating 3rd-party Java components: charts/graphs/widgets/reports</li>
</ul>
</li>
<li>Advanced Matlab-Java GUI
<ul>
<li>Customizing standard Matlab uicontrols</li>
<li>Figure-level customization (maximize/minimize, disable etc.)</li>
<li>Containers and position – Matlab vs. Java</li>
<li>Compatibility aspects and trade-offs</li>
<li>Safe programming with Java in Matlab</li>
<li>Java&#8217;s EDT and timing considerations</li>
<li>Deployment (compiler) aspects</li>
</ul>
</li>
</ol>
<p>At the end of this seminar, you will have learned how to:</p>
<ul>
<li>customize the figure toolbar and main menu</li>
<li>use HTML to format GUI appearance</li>
<li>integrate Java controls in Matlab GUI</li>
<li>customize your Matlab GUI to a degree that you never knew was possible</li>
<li>create a modern-looking professional GUI in Matlab</li>
</ul>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-gui-training-seminars-zurich-29-30-august-2017">Matlab GUI training seminars &#8211; Zurich, 29-30 August 2017</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/matlab-expo-bern-22-june-2017" rel="bookmark" title="Matlab Expo &#8211; Bern, 22 June 2017">Matlab Expo &#8211; Bern, 22 June 2017 </a> <small>I will be speaking about easy-to-use Matlab tricks at the upcoming Matlab Expo in Bern, Switzerland on June 22, 2017. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/findjobj-find-underlying-java-object" rel="bookmark" title="FindJObj &#8211; find a Matlab component&#039;s underlying Java object">FindJObj &#8211; find a Matlab component&#039;s underlying Java object </a> <small>The FindJObj utility can be used to access and display the internal components of Matlab controls and containers. This article explains its uses and inner mechanism....</small></li>
<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/training" rel="bookmark" title="New training courses">New training courses </a> <small>I am now offering a new service of professional Matlab training, at your location. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-gui-training-seminars-zurich-29-30-august-2017/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Listbox selection hacks</title>
		<link>https://undocumentedmatlab.com/articles/listbox-selection-hacks?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=listbox-selection-hacks</link>
					<comments>https://undocumentedmatlab.com/articles/listbox-selection-hacks#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 13 Jul 2016 15:36:19 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[uicontrol]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6534</guid>

					<description><![CDATA[<p>Matlab listbox selection can be customized in a variety of undocumented ways. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/listbox-selection-hacks">Listbox selection hacks</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-listbox-combobox-items" rel="bookmark" title="Customizing listbox/combobox items">Customizing listbox/combobox items </a> <small>Matlab listboxes can be customized using custom Java cell-renderers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/additional-uicontrol-tooltip-hacks" rel="bookmark" title="Additional uicontrol tooltip hacks">Additional uicontrol tooltip hacks </a> <small>Matlab's uicontrol tooltips have several limitations that can be overcome using the control's underlying Java object....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-listbox-mouse-actions" rel="bookmark" title="Setting listbox mouse actions">Setting listbox mouse actions </a> <small>Matlab listbox uicontrol can be modified to detect mouse events for right-click context menus, dynamic tooltips etc....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/smart-listbox-editbox-scrollbars" rel="bookmark" title="Smart listbox &amp; editbox scrollbars">Smart listbox &amp; editbox scrollbars </a> <small>Matlab listbox and multi-line editbox scrollbars can easily be made smarter, for improved appearance. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Last week a reader on the CSSM newsgroup <a href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/115782" rel="nofollow" target="_blank">asked</a> whether it is possible to programmatically deselect all listbox items. By default, Matlab listboxes enable a single item selection: trying to deselect it interactively has no effect, while trying to set the listbox&#8217;s <b>Value</b> property to empty ([]) results in the listbox disappearing and a warning issued to the Matlab console:<br />
<span class="alignright"><img decoding="async" src="https://undocumentedmatlab.com/images/Listbox_SINGLE_SELECTION.png" title="Single-selection Matlab listbox" alt="Single-selection Matlab listbox" width="90" height="105" /><span></p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; hListbox = <span style="color: #0000FF;">uicontrol</span><span style="color: #080;">(</span><span style="color:#A020F0;">'Style'</span>,<span style="color:#A020F0;">'list'</span>, <span style="color:#A020F0;">'String'</span>,<span style="color: #080;">{</span><span style="color:#A020F0;">'item #1'</span>,<span style="color:#A020F0;">'item #2'</span>,<span style="color:#A020F0;">'item #3'</span>,<span style="color:#A020F0;">'item #4'</span>,<span style="color:#A020F0;">'item #5'</span>,<span style="color:#A020F0;">'item #6'</span><span style="color: #080;">}</span><span style="color: #080;">)</span>;
&gt;&gt; <span style="color: #0000FF;">set</span><span style="color: #080;">(</span>hListbox,<span style="color:#A020F0;">'Value'</span>,<span style="color: #080;">[</span><span style="color: #080;">]</span><span style="color: #080;">)</span>;
<span style="color: #F5B666;">Warning: Single-selection 'listbox' control requires a scalar Value.
Control will not be rendered until all of its parameter values are valid
(Type "<u>warning off MATLAB:hg:uicontrol:ValueMustBeScalar</u>" to suppress this warning.)</span></pre>
</div>
</div>
<p>The reader&#8217;s question was whether there is a way to bypass this limitation so that no listbox item will be selected. The answer to this question was provided by MathWorker Steve(n) Lord. Steve is a very long-time benefactor of the Matlab community with endless, tireless, and patient advise to queries small and large (way beyond the point that would have frustrated mere mortals). Steve <a href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/115782#946783" rel="nofollow" target="_blank">pointed out</a> that by default, Matlab listboxes only enable a single selection &#8211; not more and not less. However, when the listbox&#8217;s <b>Max</b> value is set to be >1, the listbox enables multiple-items selection, meaning that <b>Value</b> accepts and reports an array of item indices, and there is nothing that prevents this array from being empty (meaning no items selected):</p>
<pre lang="matlab">
>> hListbox = uicontrol('Style','list', 'Max',2, 'String',{'item #1','item #2','item #3','item #4','item #5','item #6'});
>> set(hListbox,'Value',[]);  % this is ok - listbox appears with no items selected
</pre>
<p>Note: actually, the listbox checks the value of <b>Max</b>&#8211;<b>Min</b>, but by default <b>Min</b>=0 and there is really no reason to modify this default value, just <b>Max</b>.<br />
While this makes sense if you think about it, <a href="http://www.mathworks.com/help/matlab/ref/uicontrol-properties.html#property_max" rel="nofollow" target="_blank">the existing documentation</a> makes no mention of this fact:<br />
<span id="more-6534"></span></p>
<blockquote><p>The Max property value helps determine whether the user can select multiple items in the list box simultaneously. If Max – Min > 1, then the user can select multiple items simultaneously. Otherwise, the user cannot select multiple items simultaneously. If you set the Max and Min properties to allow multiple selections, then the Value property value can be a vector of indices.</p></blockquote>
<p>Some readers might think that this feature is not really <i>undocumented</i>, since it does not directly conflict with the documentation text, but then so are many other undocumented aspects and features on this blog, which are not mentioned anywhere in the official documentation. I contend that if this feature is officially supported, then it deserves an explicit sentence in the official documentation.<br />
However, the original CSSM reader wanted to preserve Matlab&#8217;s single-selection model while enabling deselection of an item. Basically, the reader wanted a selection model that enables 0 or 1 selections, but not 2 or more. This requires some tweaking using the listbox&#8217;s selection callback:</p>
<pre lang="matlab">
set(hListbox,'Callback',@myCallbackFunc);
...
function test(hListbox, eventData)
   value = get(hListbox, 'Value');
   if numel(value) > 1
       set(hListbox, 'Value', value(1));
   end
end
</pre>
<p>&#8230;or a callback-function version that is a bit better because it takes the previous selection into account and tries to set the new selection to the latest-selected item (this works in most cases, but not with shift-clicks as explained below):</p>
<pre lang="matlab">
function myCallbackFunc(hListbox, eventData)
   lastValue = getappdata(hListbox, 'lastValue');
   value = get(hListbox, 'Value');
   if ~isequal(value, lastValue)
      value2 = setdiff(value, lastValue);
      if isempty(value2)
         setappdata(hListbox, 'lastValue', value);
      else
         value = value2(1);  % see quirk below
         setappdata(hListbox, 'lastValue', value);
         set(hListbox, 'Value', value);
      end
   end
end
</pre>
<p>This does the job of enabling only a single selection at the same time as allowing the user to interactively deselect that item (by ctrl-clicking it).<br />
There&#8217;s just a few quirks: If the user selects a block of items (using shift-click), then only the second-from-top item in the block is selected, rather than the expected last-selected item. This is due to line #9 in the callback code which selects the first value. Matlab does not provide us with information about which item was clicked, so this cannot be helped using pure Matlab. Another quirk that cannot easily be solved using pure Matlab is the flicker that occurs when the selection changes and is then corrected by the callback.<br />
We can solve both of these problems using the listbox&#8217;s underlying Java component, which we can retrieve using my <a href="/articles/findjobj-find-underlying-java-object" target="_blank"><i><b>findjobj</b></i> utility</a>:</p>
<pre lang="matlab">
% No need for the standard Matlab callback now
set(hListbox,'Callback',[]);
% Get the underlying Java component peer
jScrollPane = findjobj(h);
jListbox = jScrollPane.getViewport.getView;
jListbox = handle(jListbox,'CallbackProperties');  % enable callbacks
% Attach our callback to the listbox's Java peer
jListbox.ValueChangedCallback = {@myCallbackFunc, hListbox};
...
function myCallbackFunc(jListbox, eventData, hListbox)
   if numel(jListbox.getSelectedIndices) > 1
      set(hListbox, 'Value', jListbox.getLeadSelectionIndex+1);  % +1 because Java indices start at 0
   end
end
</pre>
<p>We can use a similar mechanism to control other aspects of selection, for example to enable only up to 3 selections but no more etc.<br />
We can use this underlying Java component peer for a few other useful selection-related hacks: First, we can use the peer&#8217;s <b>RightSelectionEnabled</b> property or <i>setRightSelectionEnabled()</i> method to enable the user to select by right-clicking listbox items (this is disabled by default):</p>
<pre lang="matlab">
jListbox.setRightSelectionEnabled(true);  % false by default
set(jListbox,'RightSelectionEnabled',true);  % equivalent alternative
</pre>
<p>A similarly useful property is <b>DragSelectionEnabled</b> (or the corresponding <i>setDragSelectionEnabled()</i> method), which is true by default, and controls whether the selection is extended to other items when the mouse drags an item up or down the listbox.<br />
Finally, we can control whether in multi-selection mode we enable the user to only select a single contiguous block of items, or not (which is Matlab&#8217;s default behavior). This is set via the <b>SelectionMode</b> property (or associated <i>setSelectionMode()</i> method), as follows:</p>
<pre lang="matlab">
jListbox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
jListbox.setSelectionMode(1);  % equivalent alternative (less maintainable/readable, but simpler)
</pre>
<p><center></p>
<table style="text-align:center; width:650px;">
<tr>
<td><img loading="lazy" decoding="async" alt="SINGLE_SELECTION (default for Max=1)" src="https://undocumentedmatlab.com/images/Listbox_SINGLE_SELECTION.png" title="SINGLE_SELECTION (default for Max=1)" width="60" height="70" /></td>
<td><img loading="lazy" decoding="async" alt="SINGLE_INTERVAL_SELECTION (only possible with Java)" src="https://undocumentedmatlab.com/images/Listbox_SINGLE_INTERVAL_SELECTION.png" title="SINGLE_INTERVAL_SELECTION (only possible with Java)" width="60" height="70" /></td>
<td><img loading="lazy" decoding="async" alt="MULTIPLE_INTERVAL_SELECTION (default for Max&gt;1)" src="https://undocumentedmatlab.com/images/Listbox_MULTIPLE_INTERVAL_SELECTION.png" title="MULTIPLE_INTERVAL_SELECTION (default for Max&gt;1)" width="60" height="70" /></td>
</tr>
<tr>
<td><code>SINGLE_SELECTION</code> =0</td>
<td><code>SINGLE_INTERVAL_SELECTION</code> =1</td>
<td><code>MULTIPLE_INTERVAL_SELECTION</code> =2</td>
</tr>
<tr>
<td>(Matlab default for <b>Max</b>=1)</td>
<td>(only possible with Java)</td>
<td>(Matlab default for <b>Max</b>&gt;1)</td>
</tr>
</table>
<p></center><br />
Additional listbox customizations can be found in related posts on this blog (see links below), or in section 6.6 of my <a href="/books/matlab-java" target="_blank">Matlab-Java Programming Secrets book</a> (which is still selling nicely almost five years after its publication, to the pleasant surprise of my publisher&#8230;).</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/listbox-selection-hacks">Listbox selection hacks</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-listbox-combobox-items" rel="bookmark" title="Customizing listbox/combobox items">Customizing listbox/combobox items </a> <small>Matlab listboxes can be customized using custom Java cell-renderers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/additional-uicontrol-tooltip-hacks" rel="bookmark" title="Additional uicontrol tooltip hacks">Additional uicontrol tooltip hacks </a> <small>Matlab's uicontrol tooltips have several limitations that can be overcome using the control's underlying Java object....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-listbox-mouse-actions" rel="bookmark" title="Setting listbox mouse actions">Setting listbox mouse actions </a> <small>Matlab listbox uicontrol can be modified to detect mouse events for right-click context menus, dynamic tooltips etc....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/smart-listbox-editbox-scrollbars" rel="bookmark" title="Smart listbox &amp; editbox scrollbars">Smart listbox &amp; editbox scrollbars </a> <small>Matlab listbox and multi-line editbox scrollbars can easily be made smarter, for improved appearance. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/listbox-selection-hacks/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Figure keypress modifiers</title>
		<link>https://undocumentedmatlab.com/articles/figure-keypress-modifiers?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=figure-keypress-modifiers</link>
					<comments>https://undocumentedmatlab.com/articles/figure-keypress-modifiers#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 04 Nov 2015 21:19:59 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6059</guid>

					<description><![CDATA[<p>The figure's CurrentModifier property provides a simple and consistent way to retrieve keypress modifiers: alt-, control- and shift-clicks. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/figure-keypress-modifiers">Figure keypress modifiers</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/uicontrol-side-effect-removing-figure-toolbar" rel="bookmark" title="uicontrol side-effect: removing figure toolbar">uicontrol side-effect: removing figure toolbar </a> <small>Matlab's built-in uicontrol function has a side-effect of removing the figure toolbar. This was undocumented until lately. This article describes the side-effect behavior and how to fix it....</small></li>
<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/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>
<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>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab figures have a documented property called <b><a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/figure-properties.html#property_selectiontype">SelectionType</a></b> that returns information about keypress modifiers such as <shift> or <control> that were pressed during mouse clicks. Using this property has several drawbacks IMHO:</p>
<ul>
<li>The reported <b>SelectionType</b> value is <code>'extend'</code> for shift-clicks and <code>'alt'</code> for ctrl-clicks, not very intuitive.</li>
<li>There is no support for alt-clicks, which are reported as regular (<code>'normal'</code>) mouse clicks. In fact, <code>'alt'</code> is reported for ctrl-clicks rather than for alt-clicks, which is very confusing.</li>
<li>There is no support for modifier combinations such as ctrl+shift-click. These again are reported as regular (<code>'normal'</code>) mouse clicks.</li>
<li><b>SelectionType</b> is only updated for mouse clicks, not for keyboard clicks. This again is very confusing. To extract the keypress modifier for key-click events we need to get the <b>Modifier</b> property of the key-press event, and this returns a cell-array of strings (e.g., <code>{'shift','control','alt'}</code>). Note that in this case, unlike <b>SelectionType</b>, the modifier names are as expected, alt-clicks is recognised and so are modifier combinations.</li>
</ul>
<pre lang='matlab'>
% Documented: we need to get the modifier data in two different manners
set(gcf, 'WindowButtonDownFcn', @(h,e) disp(get(gcf,'SelectionType')));  % mouse clicks: displays a single string: 'normal','alt','extend' or 'open'
set(gcf, 'WindowKeyPressFcn',   @(h,e) disp(e.Modifier));  % keyboard clicks: displays a cell-array of strings, e.g. {'shift','control','alt'}
</pre>
<p>The inconsistency between the functionality for mouse and keyboard clicks, and the limitations of the <b>SelectionType</b> property, are striking and most annoying. Some might say that it&#8217;s been like this for the past 2 decades so Matlab users have probably gotten used to it by now. But I must admit that after over 2 decades with Matlab I still need to refer to the documentation to figure out the correct behavior. Maybe that&#8217;s because I&#8217;m getting old, or maybe it means that the behavior is indeed not as intuitive as one could hope for.<br />
For this reason, I was very happy to discover several years ago that there was a much simpler, easier and consistent solution, although (alas) undocumented. The trick is to simply query the undocumented hidden figure property <b>CurrentModifier</b>:<span id="more-6059"></span> <b>CurrentModifier</b> is updated during both mouse and keyboard clicks, in the same consistent manner, in both cases returning the same cell-array of strings as the <b>Modifier</b> property of the standard key-press event:</p>
<pre lang='matlab'>
% Undocumented: the following displays a cell-array of strings having a consistent format, e.g. {'shift','control','alt'}
set(gcf, 'WindowButtonDownFcn', @(h,e) disp(get(gcf,'CurrentModifier')));  % mouse clicks
set(gcf, 'WindowKeyPressFcn',   @(h,e) disp(get(gcf,'CurrentModifier')));  % keyboard clicks
</pre>
<p>Checking whether any modifier was pressed becomes trivial:</p>
<pre lang='matlab'>
modifiers = get(gcf,'CurrentModifier');
wasShiftPressed = ismember('shift',   modifiers);  % true/false
wasCtrlPressed  = ismember('control', modifiers);  % true/false
wasAltPressed   = ismember('alt',     modifiers);  % true/false
</pre>
<p>Hurrah for simplicity and consistency!<br />
Note that despite the fact that <b>CurrentModifier</b> is hidden and undocumented, it has existed as-is for many years, and even survived (unchanged) the major transition from HG1 to HG2 in R2014b. This has to mean that MathWorks recognized the importance of <b>CurrentModifier</b> and took the deliberate decision (and associate dev effort) to preserve it. So why wasn&#8217;t this useful property made documented ages ago, or at the very least at the HG2 transition point? I don&#8217;t have a good answer to this riddle.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/figure-keypress-modifiers">Figure keypress modifiers</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/uicontrol-side-effect-removing-figure-toolbar" rel="bookmark" title="uicontrol side-effect: removing figure toolbar">uicontrol side-effect: removing figure toolbar </a> <small>Matlab's built-in uicontrol function has a side-effect of removing the figure toolbar. This was undocumented until lately. This article describes the side-effect behavior and how to fix it....</small></li>
<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/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>
<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>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/figure-keypress-modifiers/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Callback functions performance</title>
		<link>https://undocumentedmatlab.com/articles/callback-functions-performance?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=callback-functions-performance</link>
					<comments>https://undocumentedmatlab.com/articles/callback-functions-performance#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 09 Sep 2015 23:36:25 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[JIT]]></category>
		<category><![CDATA[LXE]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5996</guid>

					<description><![CDATA[<p>Using anonymous functions in Matlab callbacks can be very painful for performance. Today's article explains how this can be avoided. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/callback-functions-performance">Callback functions performance</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/matlab-java-memory-leaks-performance" rel="bookmark" title="Matlab-Java memory leaks, performance">Matlab-Java memory leaks, performance </a> <small>Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/controlling-callback-re-entrancy" rel="bookmark" title="Controlling callback re-entrancy">Controlling callback re-entrancy </a> <small>Callback reentrancy is a major problem for frequently-fired events. Luckily, it can easily be solved....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/continuous-slider-callback" rel="bookmark" title="Continuous slider callback">Continuous slider callback </a> <small>Matlab slider uicontrols do not enable a continuous-motion callback by default. This article explains how this can be achieved using undocumented features....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-mouse-pointer-functions" rel="bookmark" title="Undocumented mouse pointer functions">Undocumented mouse pointer functions </a> <small>Matlab contains several well-documented functions and properties for the mouse pointer. However, some very-useful functions have remained undocumented and unsupported. This post details their usage....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab enables a variety of ways to define callbacks for asynchronous events (such as interactive GUI actions or timer invocations). We can provide a function handle, a cell-array (of function handle and extra parameters), and in some cases also a string that will be <i><b>eval</b></i>&#8216;ed in run-time. For example:</p>
<pre lang='matlab'>
hButton = uicontrol(..., 'Callback', @myCallbackFunc);  % function handle
hButton = uicontrol(..., 'Callback', {@myCallbackFunc,data1,data2});  % cell-array
hButton = uicontrol(..., 'Callback', 'disp clicked!');  % string to eval
</pre>
<p>The first format, function handle, is by far the most common in Matlab code. This format has two variant: we can specify the direct handle to the function (as in <code>@myCallbackFunc</code>), or we could use an anonymous function, like this:</p>
<pre lang='matlab'>hButton = uicontrol(..., 'Callback', @(h,e) myCallbackFunc(h,e));  % anonymous function handle</pre>
<p>All Matlab callbacks accept two input args by default: the control&#8217;s handle (hButton in this example), and a struct or object that contain the event&#8217;s data in internal fields. In our anonymous function variant, we therefore defined a function that accepts two input args (h,e) and calls myCallbackFunc(h,e).<br />
These two variants are functionally equivalent:</p>
<pre lang='matlab'>
hButton = uicontrol(..., 'Callback', @myCallbackFunc);             % direct function handle
hButton = uicontrol(..., 'Callback', @(h,e) myCallbackFunc(h,e));  % anonymous function handle
</pre>
<p>In my experience, the anonymous function variant is widely used &#8211; I see it extensively in many of my consulting clients&#8217; code. Unfortunately, there could be a huge performance penalty when using this variant compared to a direct function handle, which many people are simply not aware of. I believe that even many MathWorkers are not aware of this, based on a recent conversation I&#8217;ve had with someone in the know, as well as from the numerous usage examples in internal Matlab code: see the screenshot below for some examples; there are numerous others scattered throughout the Matlab code corpus.<span id="more-5996"></span><br />
Part of the reason for this penalty not being well known may be that Matlab&#8217;s Profiler does not directly attribute the overheads. Here is a typical screenshot:<br />
<center><figure style="width: 395px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Profiling anonymous callback function performance" src="https://undocumentedmatlab.com/images/anon_func_performance.jpg" title="Profiling anonymous callback function performance" width="395" height="437" /><figcaption class="wp-caption-text">Profiling anonymous callback function performance</figcaption></figure></center><br />
In this example, a heavily-laden GUI figure window was closed, triggering multiple cleanup callbacks, most of them belonging to internal Matlab code. Closing the figure took a whopping 8 secs. As can be seen from the screenshot, the callbacks themselves only take ~0.66 secs, and an additional 7.4 secs (92% of the total) is unattributed to any specific line. Think about it for a moment: we can only really see what&#8217;s happening in 8% of the time &#8211; the Profiler provides no clue about the root cause of the remaining 92%.<br />
The solution in this case was to notice that the callback was defined using an anonymous function, <code>@(h,e)obj.tableDeletedCallbackFcn(e)</code>. Changing all such instances to <code>@obj.tableDeletedCallbackFcn</code> (the function interface naturally needed to change to accept h as the first input arg) drastically cut the processing time, since direct function handles do not carry the same performance overheads as anonymous functions. In this specific example, closing the figure window now became almost instantaneous (<1 sec).


<h3 id="conclusions">Conclusions</h3>
<p>There are several morals that I think can be gained from this:</p>
<ol>
<li>When we see unattributed time in the Profiler summary report, odds are high that this is due to function-call overheads. MathWorks have significantly reduced such overheads in the new R2015b (released last week), but anonymous [and to some degree also class methods] functions still carry a non-negligible invocation overheads that should be avoided if possible, by using direct [possibly non-MCOS] functions.</li>
<li>Use direct function handles rather than anonymous function handles, wherever possible</li>
<li>In the future, MathWorks will hopefully improve Matlab&#8217;s new engine (&#8220;LXE&#8221;) to automatically identify cases of <code>@(h,e)func(h,e)</code> and replace them with faster calls to <code>@func</code>, but in any case it would be wise to manually make this change in our code today. It would immediately improve readability, maintainability and performance, while still being entirely future-compatible.</li>
<li>In the future, MathWorks may also possibly improve the overheads of anonymous function invocations. This is more tricky than the straight-forward lexical substitution above, because anonymous functions need to carry the run-time workspace with them. This is a little known and certainly very little-used fact, which means that in practice most usage patterns of anonymous functions can be statically analyzed and converted into much faster direct function handles that carry no run-time workspace info. This is indeed tricky, but it could directly improve performance of many Matlab programs that naively use anonymous functions.</li>
<li>Matlab&#8217;s Profiler should really be improved to provide more information about unattributed time spent in internal Matlab code, to provide users clues that would help them reduce it. Some information could be gained by using the <a target="_blank" href="/articles/undocumented-profiler-options-part-4">Profiler&#8217;s <code>-detail builtin</code> input args</a> (which was documented until several releases ago, but then apparently became unsupported). I think that the Profiler should still be made to provide better insights in such cases.</li>
</ol>
<p>Oh, and did I mention already the nice work MathWorks did with 15b&#8217;s LXE? Matlab&#8217;s JIT replacement was many years in the making, possibly since the mid 2000&#8217;s. We now see just the tip of the iceberg of this new engine: I hope that additional benefits will become apparent in future releases.<br />
For a definitive benchmark of Matlab&#8217;s function-call overheads in various variants, readers are referred to <a target="_blank" rel="nofollow" href="https://github.com/apjanke/matlab-bench">Andrew Janke&#8217;s excellent utility</a> (with some pre-15b <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/1693429/is-matlab-oop-slow-or-am-i-doing-something-wrong#1745686">usage results and analysis</a>). Running this benchmark on my machine shows significant overhead reduction in function-call overheads in 15b in many (but not all) invocation types.<br />
For those people wondering, 15b&#8217;s LXE does improve HG2&#8217;s performance, but just by a small bit &#8211; still not enough to offset the large performance hit of HG2 vs. HG1 in several key aspects. MathWorks is <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/337755#937008">actively working</a> to improve HG2&#8217;s performance, but unfortunately there is still no breakthrough as of 15b.<br />
Additional details on various performance issues related to Matlab function calls (and graphics and anything else in Matlab) can be found in my recent book, <a target="_blank" href="/books/matlab-performance"><b>Accelerating MATLAB Performance</b></a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/callback-functions-performance">Callback functions performance</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/matlab-java-memory-leaks-performance" rel="bookmark" title="Matlab-Java memory leaks, performance">Matlab-Java memory leaks, performance </a> <small>Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/controlling-callback-re-entrancy" rel="bookmark" title="Controlling callback re-entrancy">Controlling callback re-entrancy </a> <small>Callback reentrancy is a major problem for frequently-fired events. Luckily, it can easily be solved....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/continuous-slider-callback" rel="bookmark" title="Continuous slider callback">Continuous slider callback </a> <small>Matlab slider uicontrols do not enable a continuous-motion callback by default. This article explains how this can be achieved using undocumented features....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-mouse-pointer-functions" rel="bookmark" title="Undocumented mouse pointer functions">Undocumented mouse pointer functions </a> <small>Matlab contains several well-documented functions and properties for the mouse pointer. However, some very-useful functions have remained undocumented and unsupported. This post details their usage....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/callback-functions-performance/feed</wfw:commentRss>
			<slash:comments>12</slash:comments>
		
		
			</item>
		<item>
		<title>Undocumented HG2 graphics events</title>
		<link>https://undocumentedmatlab.com/articles/undocumented-hg2-graphics-events?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=undocumented-hg2-graphics-events</link>
					<comments>https://undocumentedmatlab.com/articles/undocumented-hg2-graphics-events#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 27 May 2015 17:20:10 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Listeners]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Listener]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5806</guid>

					<description><![CDATA[<p>Matlab's new HG2 graphics engine includes many new undocumented events that could be used in various ways. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-hg2-graphics-events">Undocumented HG2 graphics events</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/udd-events-and-listeners" rel="bookmark" title="UDD Events and Listeners">UDD Events and Listeners </a> <small>UDD event listeners can be used to listen to property value changes and other important events of Matlab objects...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-graphics-behavior" rel="bookmark" title="Handle Graphics Behavior">Handle Graphics Behavior </a> <small>HG behaviors are an important aspect of Matlab graphics that enable custom control of handle functionality. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events" rel="bookmark" title="Matlab callbacks for Java events">Matlab callbacks for Java events </a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/improving-graphics-interactivity" rel="bookmark" title="Improving graphics interactivity">Improving graphics interactivity </a> <small>Matlab R2018b added default axes mouse interactivity at the expense of performance. Luckily, we can speed-up the default axes. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>R2014b brought a refreshing new graphics engine and appearance, internally called HG2 (the official marketing name is long and impossible to remember, and certainly not as catchy). I&#8217;ve already posted a <a target="_blank" href="/articles/tag/hg2">series of articles about HG2</a>. Today I wish to discuss an undocumented aspect of HG2 that I&#8217;ve encountered several times over the past months, and most recently today. The problem is that while in the previous HG1 system (R2014a and earlier) we could add property-change listener callbacks to practically any graphics object, this is no longer true for HG2. Many graphics properties, that are calculated on-the-fly based on other property values, cannot be listened-to, and so we cannot attach callbacks that trigger when their values change.</p>
<h3 id="HG1">Property-change listeners in HG1</h3>
<p>Take for example my post about <a target="_blank" href="/articles/setting-axes-tick-labels-format">setting axes tick labels format</a> from 3 years ago: the idea there was to attach a Matlab callback function to the <code>PropertyPostSet</code> event of the <b>XTick</b>, <b>YTick</b> and/or <b>ZTick</b> properties, so that when they change their values (upon zoom/pan/resize), the corresponding tick-labels would be reformatted based on the user-specified format:<br />
<center><figure style="width: 300px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/PlotLabels_2a.png" alt="Formatted labels, automatically updated" title="Formatted labels, automatically updated" width="134" height="143" /> <img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/PlotLabels_2b.png" alt="Formatted labels, automatically updated" title="Formatted labels, automatically updated" width="134" height="143" /><figcaption class="wp-caption-text">Formatted labels, automatically updated</figcaption></figure></center><br />
<span id="more-5806"></span><br />
A simple HG1 usage might look as follows:</p>
<pre lang='matlab'>
addlistener(handle(hAxes), 'YTick', 'PostSet', @reformatTickLabels);
function reformatTickLabels(hProperty, eventData)
    try
        hAxes = eventData.AffectedObject;
    catch
        hAxes = ancestor(eventData.Source,'Axes');
    end
    tickValues = get(hAxes, 'YTick');
    tickLabels = arrayfun(@(x)(sprintf('%.1fV',x)), tickValues, 'UniformOutput',false);
    set(hAxes, 'YTickLabel', tickLabels)
end
</pre>
<p>I prepared a utility called <i><b>ticklabelformat</b></i> that automates much of the set-up above. Feel free to <a target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/36254-ticklabelformat">download</a> this utility from the Matlab File Exchange. Its usage syntax is as follows:</p>
<pre lang='matlab'>
ticklabelformat(gca,'y','%.6g V')  % sets y axis on current axes to display 6 significant digits
ticklabelformat(gca,'xy','%.2f')   % sets x & y axes on current axes to display 2 decimal digits
ticklabelformat(gca,'z',@myCbFcn)  % sets a function to update the Z tick labels on current axes
ticklabelformat(gca,'z',{@myCbFcn,extraData})  % sets an update function as above, with extra data
</pre>
<h3 id="HGs">Property-change listeners in HG2</h3>
<p>Unfortunately, this fails in HG2 when trying to listen to automatically-recalculated (non-<code>Observable</code>) properties such as the <b>Position</b> or axes <b>Tick</b> properties. We can only listen to non-calculated (<code>Observable</code>) properties such as <b>Tag</b> or <b>YLim</b>. Readers might think that this answers the need, since the ticks change when the axes limits change. This is true, but does not cover all cases. For example, when we resize/maximize the figure, Matlab may decide to modify the displayed ticks, although the axes limits remain unchanged.<br />
So we need to have a way to monitor changes even in auto-calculated properties. Luckily this can be done by listening to a set of new undocumented HG2 events. It turns out that HG2&#8217;s axes (<code>matlab.graphics.axis.Axes</code> objects) have no less than 17 declared events, and 14 of them are hidden in R2015a:</p>
<pre lang='matlab' highlight='22'>
>> events(gca)   % list the non-hidden axes events
Events for class matlab.graphics.axis.Axes:
    ObjectBeingDestroyed
    PropertyAdded
    PropertyRemoved
>> mc = metaclass(gca)
mc =
  GraphicsMetaClass with properties:
                     Name: 'matlab.graphics.axis.Axes'
              Description: 'TODO: Fill in Description'
      DetailedDescription: ''
                   Hidden: 0
                   Sealed: 1
                 Abstract: 0
              Enumeration: 0
          ConstructOnLoad: 1
         HandleCompatible: 1
          InferiorClasses: {0x1 cell}
        ContainingPackage: [1x1 meta.package]
             PropertyList: [414x1 meta.property]
               MethodList: [79x1 meta.method]
                EventList: [17x1 meta.event]
    EnumerationMemberList: [0x1 meta.EnumeratedValue]
           SuperclassList: [7x1 meta.class]
>> mc.EventList(10)
ans =
  event with properties:
                   Name: 'MarkedClean'
            Description: 'description'
    DetailedDescription: 'detailed description'
                 Hidden: 1
           NotifyAccess: 'public'
           ListenAccess: 'public'
          DefiningClass: [1x1 matlab.graphics.internal.GraphicsMetaClass]
>> [{mc.EventList.Name}; ...
    {mc.EventList.ListenAccess}; ...
    arrayfun(@mat2str, [mc.EventList.Hidden], 'Uniform',false)]'
ans =
    'LocationChanged'             'public'       'true'
    'SizeChanged'                 'public'       'true'
    'ClaReset'                    'public'       'true'
    'ClaPreReset'                 'public'       'true'
    'Cla'                         'public'       'true'
    'ObjectBeingDestroyed'        'public'       'false'  % not hidden
    'Hit'                         'public'       'true'
    'LegendableObjectsUpdated'    'public'       'true'
    'MarkedDirty'                 'public'       'true'
    'MarkedClean'                 'public'       'true'
    'PreUpdate'                   'protected'    'true'
    'PostUpdate'                  'protected'    'true'
    'Error'                       'public'       'true'
    'Reparent'                    'public'       'true'
    'Reset'                       'public'       'true'
    'PropertyAdded'               'public'       'false'  % not hidden
    'PropertyRemoved'             'public'       'false'  % not hidden
</pre>
<p>Similar hidden events exist for all HG2 graphics objects. The <code>MarkedDirty</code> and <code>MarkedClean</code> events are available for practically all graphic objects. We can listen to them (luckily, their <code>ListenAccess</code> meta-property is defined as &#8216;public&#8217;) to get a notification whenever the corresponding object (axes, or any other graphics component such as a plot-line or <a target="_blank" href="/articles/customizing-axes-rulers">axes ruler</a> etc.) is being redrawn. We can then refresh our own properties. It makes sense to attach such callbacks to <code>MarkedClean</code> rather than <code>MarkedDirty</code>, because the property values are naturally stabled and reliable only after <code>MarkedClean</code>. In some specific cases, we might wish to listen to one of the other events, which luckily have meaningful names.<br />
For example, in my <i><b>ticklabelformat</b></i> utility I&#8217;ve implemented the following code (simplified here for readability &#8211; download the utility to see the actual code), which listens to the <code>MarkedClean</code> event on the axes&#8217; <b>YRuler</b> property:</p>
<pre lang='matlab'>
try
    % HG1 (R2014a or older)
    hAx = handle(hAxes);
    hProp = findprop(hAx, 'YTick');
    hListener = handle.listener(hAx, hProp, 'PropertyPostSet', @reformatTickLabels);
    setappdata(hAxes, 'YTickListener', hListener);  % must be persisted in order to remain in effect
catch
    % HG2 (R2014b or newer)
    addlistener(hAx, 'YTick', 'PostSet', @reformatTickLabels);
    % *Tick properties don't trigger PostSet events when updated automatically in R2014b
    %addlistener(hAx, 'YLim', 'PostSet', @reformatTickLabels);  % this solution does not cover all use-cases
    addlistener(hAx.YRuler, 'MarkedClean', @reformatTickLabels);
end
% Adjust tick labels now
reformatTickLabels(hAxes);
</pre>
<p>In some cases, the triggered event might pass some useful information in the eventData object that is passed to the callback function as the second input parameter. This data may be different for different events, and is also highly susceptible to changes across Matlab releases, so use with care. I believe that the event names themselves (<code>MarkedClean</code> etc.) are less susceptible to change across Matlab releases, but they might.</p>
<h3 id="performance">Performance aspects</h3>
<p>The <code>MarkedClean</code> event is triggered numerous times, from obvious triggers such as calling <i><b>drawnow</b></i> to less-obvious triggers such as resizing the figure or modifying a plot-line&#8217;s properties. We therefore need to be very careful that our callback function is (1) <a target="_blank" href="/articles/controlling-callback-re-entrancy">non-reentrant</a>, (2) is not active too often (e.g., more than 5 times per sec), (3) does not modify properties unnecessarily, and in general (4) executes as fast as possible. For example:</p>
<pre lang='matlab'>
function reformatTickLabels(hProperty, eventData)
    persistent inCallback
    if ~isempty(inCallback),  return;  end
    inCallback = 1;  % prevent callback re-entry (not 100% fool-proof)
    % Update labels only every 0.2 secs or more
    persistent lastTime
    try
        tnow = datenummx(clock);  % fast
    catch
        tnow = now;  % slower
    end
    ONE_SEC = 1/24/60/60;
    if ~isempty(lastTime) && tnow - lastTime < 0.2*ONE_SEC
        inCallback = [];  % re-enable callback
        return;
    end
    lastTime = tnow;
    % This is the main callback logic
    try
        hAxes = eventData.AffectedObject;
    catch
        hAxes = ancestor(eventData.Source,'Axes');
    end
    prevTickValues = getappdata(hAxes, 'YTick');
    tickValues = get(hAxes, 'YTick');
    if ~isequal(prevTickValues, tickValues)
        tickLabels = arrayfun(@(x)(sprintf('%.1fV',x)), tickValues, 'UniformOutput',false);
        set(hAxes, 'YTickLabel', tickLabels)
    end
    inCallback = [];  % re-enable callback
end
</pre>
<p>Unfortunately, it seems that retrieving some property values (such as the axes's <b>YTick</b> values) may by itself trigger the <code>MarkedClean</code> event for some reason that eludes my understanding (why should merely getting the existing values modify the graphics in any way?). Adding callback re-entrancy checks as above might alleviate the pain of such recursive callback invocations.<br />
A related performance aspect is that it could be better to listen to a sub-component's <code>MarkedClean</code> than to the parent axes' <code>MarkedClean</code>, which might be triggered more often, for changes that are entirely unrelated to the sub-component that we wish to monitor. For example, if we only monitor <b>YRuler</b>, then it makes no sense to listen to the parent axes' <code>MarkedClean</code> event that might trigger due to a change in the <b>XRuler</b>.<br />
In some cases, it may be better to listen to specific events rather than the all-encompassing <code>MarkedClean</code>. For example, if we are only concerned about changes to the <b>Position</b> property, we should listen to the <code>LocationChanged</code> and/or <code>SizeChanged</code> events (<a target="_blank" href="/articles/property-value-change-listeners#comment-348826">more details</a>).<br />
Additional graphics-related performance tips can be found in my <a target="_blank" href="/books/matlab-performance"><i>Accelerating MATLAB Performance</i></a> book.<br />
Have you used <code>MarkedClean</code> or some other undocumented HG2 event in your code for some nice effect? If so, please share your experience in a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-hg2-graphics-events">Undocumented HG2 graphics events</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/udd-events-and-listeners" rel="bookmark" title="UDD Events and Listeners">UDD Events and Listeners </a> <small>UDD event listeners can be used to listen to property value changes and other important events of Matlab objects...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-graphics-behavior" rel="bookmark" title="Handle Graphics Behavior">Handle Graphics Behavior </a> <small>HG behaviors are an important aspect of Matlab graphics that enable custom control of handle functionality. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events" rel="bookmark" title="Matlab callbacks for Java events">Matlab callbacks for Java events </a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/improving-graphics-interactivity" rel="bookmark" title="Improving graphics interactivity">Improving graphics interactivity </a> <small>Matlab R2018b added default axes mouse interactivity at the expense of performance. Luckily, we can speed-up the default axes. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/undocumented-hg2-graphics-events/feed</wfw:commentRss>
			<slash:comments>18</slash:comments>
		
		
			</item>
		<item>
		<title>copyobj behavior change in HG2</title>
		<link>https://undocumentedmatlab.com/articles/copyobj-behavior-change-in-hg2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=copyobj-behavior-change-in-hg2</link>
					<comments>https://undocumentedmatlab.com/articles/copyobj-behavior-change-in-hg2#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 13 May 2015 16:00:49 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Robert Cumming]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5797</guid>

					<description><![CDATA[<p>the behavior of Matlab's copyobj function changed in R2014b (HG2), and callbacks are no longer copied. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/copyobj-behavior-change-in-hg2">copyobj behavior change in HG2</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/property-value-change-listeners" rel="bookmark" title="Property value change listeners">Property value change listeners </a> <small>HG handle property changes can be trapped in a user-defined callback. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-graphics-behavior" rel="bookmark" title="Handle Graphics Behavior">Handle Graphics Behavior </a> <small>HG behaviors are an important aspect of Matlab graphics that enable custom control of handle functionality. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-behavior" rel="bookmark" title="Undocumented scatter plot behavior">Undocumented scatter plot behavior </a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/xlsread-functionality-change-in-r2012a" rel="bookmark" title="xlsread functionality change in R2012a">xlsread functionality change in R2012a </a> <small>The functionality of the xlsread function has changed without documentation or warning in the R2012a release. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>As a followup to last-week&#8217;s post on class-object and generic data copies, I would like to welcome back guest blogger Robert Cumming, who developed a commercial <a target="_blank" rel="nofollow" href="https://sites.google.com/site/matpihome/matlab-gui-framework">Matlab GUI framework</a>. Today, Robert will highlight a behavior change of Matlab&#8217;s <b>copyobj</b> function in HG2.</i><br />
One of the latest features that was introduced to the GUI Toolbox was the ability to <a target="_blank" rel="nofollow" href="https://sites.google.com/site/matpihome/matlab-gui-framework/matlab-undock-uipanel">undock or copy panels</a>, that would be displayed in a standalone figure window, but remain connected to the underlying class object:<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><a target="_blank" rel="nofollow" href="https://sites.google.com/site/matpihome/matlab-gui-framework/matlab-undock-uipanel"><img loading="lazy" decoding="async" alt="Panel copy in the GUI framework toolbox" src="https://undocumentedmatlab.com/images/undock-02_450x412.gif" title="Panel copy in the GUI framework toolbox" width="450" height="412" /></a><figcaption class="wp-caption-text">Panel copy in the GUI framework toolbox</figcaption></figure></center><br />
These panel copies had to remain fully functional, including all children and callbacks, and they needed to retain all connections back to the source data. In the example above I have altered the plot to show that it&#8217;s an actual copy of the data, but has separate behavior from the original panel.<br />
To simply undock a uipanel to a new figure, we can simply re parent it by updating its <b>Parent</b> property to the new figure handle. To make a copy we need to utilize the <i><b>copyobj</b></i> function, rather than re-parenting. <i><b>copyobj</b></i> can be used to make a copy of all graphic objects that are &#8220;grouped&#8221; under a common parent, placing their copy in a new parent. In HG2 (R2014b onwards) the default operation of <i><b>copyobj</b></i> has changed.<br />
<span id="more-5797"></span><br />
When I started developing this feature everything looked okay and all the objects appeared copied. However, none of the callbacks were functional and all the information stored in the object&#8217;s <b>ApplicationData</b> was missing.<br />
I had used <i><b>copyobj</b></i> in the past, so I knew that it originally worked ok, so I investigated what was happening. <a target="_blank" rel="nofollow" href="http://mathworks.com/help/matlab/graphics_transition/why-are-callbacks-not-copied.html">Matlab&#8217;s documentation for HG2 code transition</a> suggests re-running the original code to create the second object to populate the callbacks. Unfortunately, this may not be suitable in all cases. Certainly in this case it would be much harder to do, than if the original callbacks had been copied directly. Another suggestion is to use the new &#8216;lagacy&#8217; option&#8217;:</p>
<blockquote><p>copyobj(___,&#8217;legacy&#8217;) copies object callback properties and object application data. This behavior is consistent with versions of copyobj before MATLAB&reg; release R2014b.</p></blockquote>
<p>So, instead of re-running the original code to create the second object to populate the callbacks, we can simply use the new &#8216;legacy&#8217; option to copy all the callbacks and <b>ApplicationData</b>:</p>
<pre lang='matlab'>copyobj(hPanel, hNewParent, 'legacy')</pre>
<p>Note: for some reason, this new &#8216;legacy&#8217; option is mentioned in both the doc page and the above-mentioned HG2 code-transition page, but not in the often used help section (<i><b>help copyobj</b></i>). There is also no link to the relevant HG2 code-transition page in either the help section or the doc page. I find it unfortunate that for such a backward-incompatible behavior change, MathWorks has not seen fit to document the information more prominently.<br />
Other things to note (this is probably not an exhaustive list…) when you are using <i><b>copyobj</b></i>:</p>
<ul>
<li>Any event listeners won&#8217;t be copied</li>
<li>Any uicontextmenus will not be copied – it will in fact behave strangely due to the fact that it will have the uicontextmenu – but the parent is the original figure – and when you right-click on the object it will change the figure focus. For example:
<pre lang='matlab'>
hFig= figure;
ax = axes;
uic = uicontextmenu ('parent', hFig);
uim = uimenu('label','My Label', 'parent',uic);
ax.UIContextMenu = uic;
copyChildren = copyobj (ax, hFig, 'legacy');
hFig2 = figure;
copyChildren.Parent = hFig2;
</pre>
</li>
</ul>
<p>Another note on undocked copies &#8211; you will need to manage your callbacks appropriately so that the callbacks manage whether they are being run by the original figure or in a new undocked figure.</p>
<h3 id="Conclusions">Conclusions</h3>
<ol>
<li><i><b>copyobj</b></i> has changed in HG2 – but the &#8220;legacy&#8221; switch allows you to use it as before.</li>
<li>It is unfortunate that backward compatibility was not fully preserved (nor documented enough) in HG2, but at least we have an escape hatch in this case.</li>
<li>Take care with the legacy option as you may need to alter uicontextmenus and re-attach listeners as required.</li>
</ol>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/copyobj-behavior-change-in-hg2">copyobj behavior change in HG2</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/property-value-change-listeners" rel="bookmark" title="Property value change listeners">Property value change listeners </a> <small>HG handle property changes can be trapped in a user-defined callback. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-graphics-behavior" rel="bookmark" title="Handle Graphics Behavior">Handle Graphics Behavior </a> <small>HG behaviors are an important aspect of Matlab graphics that enable custom control of handle functionality. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-behavior" rel="bookmark" title="Undocumented scatter plot behavior">Undocumented scatter plot behavior </a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/xlsread-functionality-change-in-r2012a" rel="bookmark" title="xlsread functionality change in R2012a">xlsread functionality change in R2012a </a> <small>The functionality of the xlsread function has changed without documentation or warning in the R2012a release. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/copyobj-behavior-change-in-hg2/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Matlab callbacks for Java events in R2014a</title>
		<link>https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-callbacks-for-java-events-in-r2014a</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 08 May 2014 10:27:03 +0000</pubDate>
				<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Callbacks]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4814</guid>

					<description><![CDATA[<p>R2014a changed the way in which Java objects expose events as Matlab callbacks. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a">Matlab callbacks for Java events in R2014a</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/matlab-callbacks-for-java-events" rel="bookmark" title="Matlab callbacks for Java events">Matlab callbacks for Java events </a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-uifigure-javascript-events" rel="bookmark" title="Matlab callbacks for uifigure JavaScript events">Matlab callbacks for uifigure JavaScript events </a> <small>Matlab callback code can be attached to JavaScript events in web-based uifigures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uicontrol-callbacks" rel="bookmark" title="Uicontrol callbacks">Uicontrol callbacks </a> <small>This post details undocumented callbacks exposed by the underlying Java object of Matlab uicontrols, that can be used to modify the control's behavior in a multitude of different events...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-java-interface-using-static-control" rel="bookmark" title="Matlab-Java interface using a static control">Matlab-Java interface using a static control </a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Exactly five years ago, in one of this blog&#8217;s first articles, I wrote an article explaining how to <a target="_blank" href="/articles/uicontrol-callbacks">trap the standard Java Swing events in Matlab</a>, in order to achieve much more extensive behavior customizability than Matlab&#8217;s standard uicontrols. Three years ago I wrote a related article showing how to <a target="_blank" href="/articles/matlab-callbacks-for-java-events">trap any Java events as simple Matlab callbacks</a>, even those from custom Java classes. This worked very well over the years, until now.<br />
Over the past few weeks, several people have <a target="_blank" href="/articles/matlab-callbacks-for-java-events#comment-323345">commented</a> and emailed me about a problem that occurs in R2014a but not in earlier releases: Whereas Java objects in R2013b and earlier automatically exposed their public events as Matlab callbacks, they no longer do so in R2014a.<br />
As a simple example to illustrate the point, let&#8217;s take a simple Java JButton and modify its label when the mouse moves over it, using the <code>mouseEntered, mouseExited</code> events. In R2013b and earlier this was pretty easy:</p>
<pre lang='matlab'>
% Create and display a simple JButton
jButton = javax.swing.JButton('click me');
javacomponent(jButton, [50,50,80,20], gcf);
% Set the Matlab callbacks to the JButton's events
set(jButton, 'MouseEnteredCallback', @(h,e)set(jButton,'Text','NOW !!!'))
set(jButton, 'MouseExitedCallback',  @(h,e)jButton.setText('click me'))
</pre>
<p><center><img loading="lazy" decoding="async" alt="Dynamic Matlab callback behavior based on Java events" src="https://undocumentedmatlab.com/images/JButton_animated.gif" title="Dynamic Matlab callback behavior based on Java events" width="120" height="35" /></center><br />
(Note how I used two distinct variants to set the button&#8217;s text, using either the Matlabized <b>Text</b> property with the <i><b>set</b></i> function, or the standard JButton&#8217;s <i>setText()</i> method. We can use either of these variants: they are equivalent and largely a matter of personal taste, although the Java method is generally preferable.)<br />
Unfortunately, in R2014a we get an error, since the <code>jButton</code> object no longer exposes its events as Matlab callbacks:</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">set</span><span style="color: #080;">(</span>jButton, <span style="color:#A020F0;">'MouseEnteredCallback'</span>, <span style="color: #F0F;">@</span><span style="color: #080;">(</span>h,e<span style="color: #080;">)</span><span style="color: #0000FF;">set</span><span style="color: #080;">(</span>jButton,<span style="color:#A020F0;">'Text'</span>,<span style="color:#A020F0;">'NOW !!!'</span><span style="color: #080;">)</span><span style="color: #080;">)</span>
<span style="color:red;">The name 'MouseEnteredCallback' is not an accessible property for an instance of class 'javax.swing.JButton'.</span></pre>
</div>
</div>
<p><span id="more-4814"></span><br />
<!-- pre lang='matlab'>
>> set(jButton, 'MouseEnteredCallback', @(h,e)set(jButton,'Text','NOW !!!'))
The name 'MouseEnteredCallback' is not an accessible property for an instance of class 'javax.swing.JButton'.
</pre -->
<h3 id="solution">The solution &#8211; wrap the Java reference in a Matlab handle</h3>
<p>Do not set Matlab callbacks on the so-called &#8220;naked&#8221; Java reference. Instead, wrap the reference with a Matlab <i><b>handle</b></i>:</p>
<pre lang='matlab'>
>> jButton = handle(jButton, 'CallbackProperties');
hjButton =
	javahandle_withcallbacks.javax.swing.JButton
% we can now set the callbacks on jButton as before
</pre>
<p>The simple act of using the <i><b>handle</b></i> wrapper rather than the naked Java reference also prevents some memory leaks, as I explained <a target="_blank" href="/articles/uicontrol-callbacks#memory_leak">here</a>. While you&#8217;re at it, also wrap (or more precisely, auto-delegate) the Java reference with a <i><b>javaObjectEDT</b></i>, if it is a Swing GUI component, in order <a target="_blank" href="/articles/matlab-and-the-event-dispatch-thread-edt">to avoid EDT timing issues</a>. Using these wrappers form two of my six rules for safe Java programming in Matlab, that I outlined in section 1.5 of my <a target="_blank" href="/matlab-java-book">Matlab-Java programming book</a>. Anyone who followed that advice would not need to modify their code for R2014a. Even if you didn&#8217;t, the solution is quite painless: simply add the wrapper line for any Java reference whose events you wish to trap.<br />
Note that the explanation above relates to all Java objects that expose events, not just for GUI ones. I used <code>JButton</code> merely to illustrate the point.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a">Matlab callbacks for Java events in R2014a</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/matlab-callbacks-for-java-events" rel="bookmark" title="Matlab callbacks for Java events">Matlab callbacks for Java events </a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-uifigure-javascript-events" rel="bookmark" title="Matlab callbacks for uifigure JavaScript events">Matlab callbacks for uifigure JavaScript events </a> <small>Matlab callback code can be attached to JavaScript events in web-based uifigures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uicontrol-callbacks" rel="bookmark" title="Uicontrol callbacks">Uicontrol callbacks </a> <small>This post details undocumented callbacks exposed by the underlying Java object of Matlab uicontrols, that can be used to modify the control's behavior in a multitude of different events...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-java-interface-using-static-control" rel="bookmark" title="Matlab-Java interface using a static control">Matlab-Java interface using a static control </a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a/feed</wfw:commentRss>
			<slash:comments>16</slash:comments>
		
		
			</item>
		<item>
		<title>uicontextmenu performance</title>
		<link>https://undocumentedmatlab.com/articles/uicontextmenu-performance?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=uicontextmenu-performance</link>
					<comments>https://undocumentedmatlab.com/articles/uicontextmenu-performance#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 02 Apr 2014 18:00:29 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Robert Cumming]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4751</guid>

					<description><![CDATA[<p>Matlab uicontextmenus are not automatically deleted with their associated objects, leading to leaks and slow-downs. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/uicontextmenu-performance">uicontextmenu performance</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/performance-scatter-vs-line" rel="bookmark" title="Performance: scatter vs. line">Performance: scatter vs. line </a> <small>In many circumstances, the line function can generate visually-identical plots as the scatter function, much faster...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/zero-testing-performance" rel="bookmark" title="Zero-testing performance">Zero-testing performance </a> <small>Subtle changes in the way that we test for zero/non-zero entries in Matlab can have a significant performance impact. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/callback-functions-performance" rel="bookmark" title="Callback functions performance">Callback functions performance </a> <small>Using anonymous functions in Matlab callbacks can be very painful for performance. Today's article explains how this can be avoided. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I would like to introduce guest blogger Robert Cumming, an <a target="_blank" rel="nofollow" href="http://www.matpi.com">independent contractor</a> based in the UK who has recently worked on certification of the newest advanced civil aircraft. Today Robert will discuss the performance of <b>uicontextmenu</b>s in interactive GUIs, which were used extensively in flight test analysis.</i><br />
Have you ever noticed that a GUI slows down over time?  I was responsible for designing a highly complex interactive GUI, which plotted flight test data for engineers and designers to analyze data for comparison with pre-flight predictions. This involved extensive plotting of data (pressure, forces/moments, anemometry, actuator settings etc&#8230;.), where individual data points were required to have specific/customizable uicontextmenus.<br />
Matlab&#8217;s <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/uicontextmenu.html">documentation on uicontextmenus</a> discusses adding them to plots, but makes no mention of the cleaning up afterwards.<br />
Let&#8217;s start with some GUI basics. First we create a figure with a simple axes and a line:</p>
<pre lang='matlab'>
x = [-10:0.2:10];
y = x.^2;
h = figure;
ax = axes ( 'parent',h );
hplot = plot ( ax, x, y );
</pre>
<p>Adding a uicontextmenu to the plot creates extra objects:</p>
<pre lang='matlab'>
uic = uicontextmenu;
uimenu ( uic, 'Label','Menu A.1' );
set ( hplot, 'uicontextmenu',uic );
fprintf ( 'Figure (h) has %i objects\n', length ( findobj ( h ) ) );
</pre>
<p>In this instance there are 5 objects, the individual menu and uicontextmenu have created an additional 2 objects.  All of this is quite basic as you would expect.<br />
<center><figure style="width: 250px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Basic plot with a custom context menu" src="https://undocumentedmatlab.com/images/uicontextmenu1.png" title="Basic plot with a custom context menu" width="250" height="170" /><figcaption class="wp-caption-text">Basic plot with a custom context menu</figcaption></figure></center><br />
<span id="more-4751"></span><br />
We now clear the plot using <i><b>cla</b></i> and draw a new line with its own new uicontextmenu. Note that we don&#8217;t save the plot handle this time:</p>
<pre lang='matlab'>
cla ( ax );
uic = uicontextmenu;
uimenu ( uic, 'Label','Menu B.1' );
plot ( ax, x, -y , 'uicontextmenu',uic );
fprintf ( 'Figure (h) has %i objects\n', length ( findobj ( h ) ) );
</pre>
<p><center><figure style="width: 250px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Another basic plot with a new context menu" src="https://undocumentedmatlab.com/images/uicontextmenu2.png" title="Another basic plot with a new context menu" width="250" height="170" /><figcaption class="wp-caption-text">Another basic plot with a new context menu</figcaption></figure></center><br />
This time the <i><b>fprintf</b></i> line tells us that the figure has 7 objects. This may not have been expected, as the first plot was cleared and the original context menu is no longer accessible (<i><b>cla</b></i> removed the plot and the line object hplot).<br />
Let&#8217;s check these object handles:</p>
<pre lang='matlab'>
>> ishandle ( findobj( h ) )'
ans =
     1     1     1     1     1     1     1     1     1     1     1     1     1
</pre>
<p>We see that all the objects are valid handles. At first this may perhaps appear confusing: after all, the plot with &#8220;Menu A.1&#8221; was deleted. Let&#8217;s check this:</p>
<pre lang='matlab'>
>> ishandle ( hplot )
ans =
     0
>> get(hplot)
Error using handle.handle/get
Invalid or deleted object.
</pre>
<p>So it appears that although the plot line was indeed deleted, its associated context menu was not. The reason for this is that the context menu is created as a child of the figure window, not the plot. We are simply using the plot line&#8217;s <b>UIContextMenu</b> property to allow the user to obtain access to it and its associated menus.<br />
Once we understand this we can do two things:</p>
<ol>
<li>Use the same uicontextmenu for each plot</li>
<li>Built individual uicontextmenus for each plot, but remember to clean up afterwards</li>
</ol>
<h3 id="importance">Is this really such a big issue?</h3>
<p>You may be wondering how big a problem is this creation of extra objects. The answer is that for simple cases like this it is really not a big issue. But let&#8217;s consider a more realistic case where we also <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/creating_guis/writing-code-for-callbacks.html">assign callbacks</a> to the menus. First we will create a figure with an axes, for plotting on and a uicontrol edit for displaying a message:</p>
<pre lang='matlab'>
function uicontextExample
   h.main = figure;
   h.ax = axes ( 'parent',h.main, 'NextPlot','add', 'position',[0.1 0.2 0.8 0.7] );
   h.msg = uicontrol ( 'style','edit', 'units','normalized', 'position',[0.08 0.01 0.65 0.1], 'backgroundcolor','white' );
   uicontrol ( 'style','pushbutton', 'units','normalized', 'position',[0.75 0.01 0.2 0.1], 'Callback',{@RedrawX20 h}, 'string','re-draw x20' );
   redraw ( [], [], h )  % see below
end
</pre>
<p>The callback <code>redraw</code> (shown below) draws a simple curve and assigns individual uicontextmenus to each individual item in the plot. Each uicontextmenu has 12 menu items:</p>
<pre lang='matlab'>
function redraw ( obj, event, h, varargin )
   cla(h.ax);
   start = tic;
   x = -50:50;
   y = x.^2;
   for ii = 1 : length(x)
      uim = uicontextmenu ( 'parent',h.main );
      for jj = 1 : 10
         menuLabel = sprintf ( 'Menu %i.%i', ii, jj );
         uimenu ( 'parent',uim, 'Label',menuLabel, 'Callback',{@redraw h} )
      end
      xStr = sprintf ( 'X = %f', x(ii) );
      yStr = sprintf ( 'Y = %f', y(ii) );
      uimenu ( 'parent',uim, 'Label',xStr, 'Callback',{@redraw h} )
      uimenu ( 'parent',uim, 'Label',yStr, 'Callback',{@redraw h} )
      plot ( h.ax, x(ii), y(ii), 'rs', 'uicontextmenu',uim );
   end
   objs = findobj ( h.main );
   s = sprintf ( 'figure contains %i objects - drawn in %3.2f seconds', length(objs), toc(start) );
   set ( h.msg, 'string',s );
   fprintf('%s\n',s)
end
</pre>
<p>To help demonstrate the slow-down in speed, the pushbutton uicontrol will redraw the plot 20 times, and show the results from the profiler:</p>
<pre lang='matlab'>
function RedrawX20 ( obj, event, h )
   profile on
   set ( obj, 'enable','off' )
   for ii = 1 : 20
      redraw ( [], [], h );
      drawnow();
   end
   set ( obj, 'enable','on' )
   profile viewer
end
</pre>
<p>The first time we run this, on a reasonable laptop it takes 0.24 seconds to draw the figure with all the menus:<br />
<center><figure style="width: 380px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Multiple context menus assigned to individual data points" src="https://undocumentedmatlab.com/images/uicontextmenu3.png" title="Multiple context menus assigned to individual data points" width="380" height="190" /><figcaption class="wp-caption-text">Multiple context menus assigned to individual data points</figcaption></figure></center><br />
When we press the &lt;re-draw x20&gt; button we get:</p>
<pre lang='matlab'>
figure contains 2731 objects - drawn in 0.28 seconds
figure contains 4044 objects - drawn in 0.28 seconds
figure contains 5357 objects - drawn in 0.28 seconds
figure contains 6670 objects - drawn in 0.30 seconds
figure contains 7983 objects - drawn in 0.32 seconds
figure contains 9296 objects - drawn in 0.30 seconds
figure contains 10609 objects - drawn in 0.31 seconds
figure contains 11922 objects - drawn in 0.30 seconds
figure contains 13235 objects - drawn in 0.32 seconds
figure contains 14548 objects - drawn in 0.30 seconds
figure contains 15861 objects - drawn in 0.31 seconds
figure contains 17174 objects - drawn in 0.31 seconds
figure contains 18487 objects - drawn in 0.32 seconds
figure contains 19800 objects - drawn in 0.33 seconds
figure contains 21113 objects - drawn in 0.32 seconds
figure contains 22426 objects - drawn in 0.33 seconds
figure contains 23739 objects - drawn in 0.35 seconds
figure contains 25052 objects - drawn in 0.34 seconds
figure contains 26365 objects - drawn in 0.35 seconds
figure contains 27678 objects - drawn in 0.35 seconds
</pre>
<p>The run time shows significant degradation, and we have many left-over objects. The profiler output confirms where the time is being spent:<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Profiling results - context menu creation is an evident hotspot" src="https://undocumentedmatlab.com/images/uicontextmenu4.png" title="Profiling results - context menu creation is an evident hotspot" width="450" height="285" /><figcaption class="wp-caption-text">Profiling results - context menu creation is an evident hotspot</figcaption></figure></center><br />
As expected the menus creation takes most of the time. Note that the timing that you will get on your own computer for this example may vary and the slowdown may be less noticeable.<br />
Let&#8217;s extend the example to include extra input arguments in the callback  (in this example they are not used &#8211; but in the industrial example extra input arguments are very possible, and were required by the customer):</p>
<pre lang='matlab'>
for ii=1:length(x)
   uim = uicontextmenu ( 'parent',h.main );
   for jj = 1 : 10
      menuLabel = sprintf ( 'Menu %i.%i', ii, jj );
      uimenu ( 'parent',uim, 'Label',menuLabel, 'Callback',{@redraw h 1 0 1} )
   end
   xStr = sprintf ( 'X = %f', x(ii) );
   yStr = sprintf ( 'Y = %f', y(ii) );
   uimenu ( 'parent',uim, 'Label',xStr, 'Callback',{@redraw h 1 0 1} )
   uimenu ( 'parent',uim, 'Label',yStr, 'Callback',{@redraw h 1 0 1} )
   plot ( h.ax, x(ii), y(ii), 'rs', 'uicontextmenu',uim );
end
</pre>
<p>Re-running the code and pressing &lt;re-draw x20&gt; we get:</p>
<pre lang='matlab'>
figure contains 1418 objects - drawn in 0.29 seconds
figure contains 2731 objects - drawn in 0.37 seconds
figure contains 4044 objects - drawn in 0.48 seconds
figure contains 5357 objects - drawn in 0.65 seconds
...
figure contains 23739 objects - drawn in 4.99 seconds
figure contains 25052 objects - drawn in 5.34 seconds
figure contains 26365 objects - drawn in 5.88 seconds
figure contains 27678 objects - drawn in 6.22 seconds
</pre>
<p>Note that the 6.22 seconds is just the time that it took the last individual redraw, not the total time to draw 20 times (which was just over a minute). The profiler is again used to confirm that the vast majority of the time (57 seconds) was spent in the <i><b>uimenu</b></i> calls, mostly on line #23. In comparison, all other lines together took just 4 seconds to run.<br />
The simple act of adding extra inputs to the callback has completely transformed the speed of our code.<br />
How real is this example?<br />
In code written for a customer, the context menu had a variety of sub menus (dependent on the parameter being plotted &#8211; from 5 to ~20), and they each had multiple parameters passed into the callbacks. Over a relatively short period of time the user would cycle through a lot of data and the number of uicontextmenus being created was surprisingly large. For example, users would easily look at 100 individual sensors recorded at 10Hz for 2 minutes (100*10*60*2). If all sensors and points are plotted individually that would be 120,000 uicontextmenus!</p>
<h3 id="solution">So how do we resolve this?</h3>
<p>The problem is addressed by simply deleting the context menu handles once they are no longer needed. This can be done by adding a <i><b>delete</b></i> command after <i><b>cla</b></i> at the top of the <code>redraw</code> function, in order to remove the redundant uicontextmenus:</p>
<pre lang='matlab' highlight='3'>
function redraw ( obj, event, h, varargin )
   cla(h.ax);
   delete ( findobj ( h.main, 'type','uicontextmenu' ) )
   set ( h.msg, 'string','redrawing' );
   start = tic;
   ...
</pre>
<p>If we now click &lt;redraw x20&gt; we see that the number of objects and the time to create them remain its essentially the same as the first call: 1418 objects and 0.28 seconds:</p>
<pre lang='matlab'>
figure contains 1418 objects - drawn in 0.28 seconds
figure contains 1418 objects - drawn in 0.30 seconds
figure contains 1418 objects - drawn in 0.33 seconds
figure contains 1418 objects - drawn in 0.29 seconds
figure contains 1418 objects - drawn in 0.29 seconds
...
</pre>
<p>Advanced users could use <a target="_blank" href="/articles/udd-events-and-listeners/">handle listeners</a> to attached a callback such that when a plot element is deleted, so too are its associated context menus.</p>
<h3 id="conclusions">Conclusions</h3>
<p>Things to consider with uicontextmenus:</p>
<ol>
<li>Always delete uicontextmenus that you have finished with.</li>
<li>If you have multiple uicontextmenus  you will want to only delete the ones associated with the axes being cleared &#8211; otherwise you will delete more than you want to.</li>
<li>Try to reduce the number of input arguments to your callbacks, group into a structure or cell array.</li>
<li>Re-use uicontextmenus where possible.</li>
</ol>
<p>Have you had similar experiences?  Or other issues where GUI slow down over time? If so, please leave a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/uicontextmenu-performance">uicontextmenu performance</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/performance-scatter-vs-line" rel="bookmark" title="Performance: scatter vs. line">Performance: scatter vs. line </a> <small>In many circumstances, the line function can generate visually-identical plots as the scatter function, much faster...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/zero-testing-performance" rel="bookmark" title="Zero-testing performance">Zero-testing performance </a> <small>Subtle changes in the way that we test for zero/non-zero entries in Matlab can have a significant performance impact. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/callback-functions-performance" rel="bookmark" title="Callback functions performance">Callback functions performance </a> <small>Using anonymous functions in Matlab callbacks can be very painful for performance. Today's article explains how this can be avoided. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/uicontextmenu-performance/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Editbox data input validation</title>
		<link>https://undocumentedmatlab.com/articles/editbox-data-input-validation?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=editbox-data-input-validation</link>
					<comments>https://undocumentedmatlab.com/articles/editbox-data-input-validation#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 02 Oct 2013 14:00:51 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[uicontrol]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4229</guid>

					<description><![CDATA[<p>Undocumented features of Matlab editbox uicontrols enable immediate user-input data validation</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/editbox-data-input-validation">Editbox data input validation</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/ip-address-input-control" rel="bookmark" title="IP address input control">IP address input control </a> <small>A built-in JIDE control can be used in Matlab GUI for IP-address entry/display. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/smart-listbox-editbox-scrollbars" rel="bookmark" title="Smart listbox &amp; editbox scrollbars">Smart listbox &amp; editbox scrollbars </a> <small>Matlab listbox and multi-line editbox scrollbars can easily be made smarter, for improved appearance. ...</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>
<li><a href="https://undocumentedmatlab.com/articles/rich-matlab-editbox-contents" rel="bookmark" title="Rich Matlab editbox contents">Rich Matlab editbox contents </a> <small>The Matlab editbox uicontrol does not handle HTML contents as do other uicontrols. In this article I show how this limitation can be removed....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Last week I <a target="_blank" href="/articles/customizing-editboxes/">explained</a> how Matlab&#8217;s editbox control can be customized using its underlying Java component. Today I extend that article by explaining how we can use this information to provide a very user-friendly input-validation function for Matlab editboxes.<br />
<center><figure style="width: 290px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Zip-code entry validation example" src="https://undocumentedmatlab.com/images/editbox_validation_animated.gif" title="Zip-code entry validation example" width="290" height="74" /><figcaption class="wp-caption-text">Zip-code entry validation example</figcaption></figure></center><br />
<span id="more-4229"></span><br />
As before, we first need to get the Matlab control&#8217;s underlying Java control. This is done using the <a target="_blank" href="/articles/findjobj-find-underlying-java-object/"><i><b>findjobj</b></i></a> utility:</p>
<pre lang='matlab'>
% Prepare the log editbox
hEditbox = uicontrol('Style','edit', 'String','Matlab', ...);
% Get the underlying Java editbox
jEditbox = findjobj(hLogPanel);
try
    % Multi-line editboxes are contained within a scroll-panel
    jEditbox = handle(jEditbox.getViewport.getView, 'CallbackProperties');
catch
    % probably a single-line editbox
end
</pre>
<h3 id="callbacks">Callbacks</h3>
<p>Once we have the <code>jEditbox</code> reference handle, we can use some ~<a target="_blank" href="/articles/uicontrol-callbacks/">30 different event callbacks that it exposes</a>. Some of the useful callbacks include:</p>
<ul>
<li><b>ActionPerformedCallback</b> – fired when &lt;enter&gt; is clicked in the editbox</li>
<li><b>CaretUpdateCallback</b> – fired when the caret position has changed</li>
<li><b>KeyTypedCallback</b> – fired whenever a keyboard button is typed when the editbox has focus</li>
</ul>
<p>For example:</p>
<pre lang='matlab'>
set(jEditbox, 'KeyPressedCallback',@myValidationFunction);
% Callback function definition
function myValidationFunction(jEditbox, eventData)
    % The following comments refer to the case of Alt-Shift-b
    keyChar = get(eventData,'KeyChar');  % or: eventData.getKeyChar  ==> 'B'
    isAltDown = get(eventData,'AltDown');  % ==> 'on'
    isAltDown = eventData.isAltDown;  % ==> true
    modifiers = get(eventData,'Modifiers');  % or: eventData.getModifiers ==> 9 = 1 (Shift) + 8 (Alt)
    modifiersDescription = char(eventData.getKeyModifiersText(modifiers));  % ==> 'Alt+Shift'
    % (now decide what to do with this key-press...)
end
</pre>
<p>Using such a validation function enables us to immediately convert typed characters into &#8216;*&#8217; (in password fields) or check that the input conforms to a standard format such as a 5-digit zip code, a valid-looking email address or a valid-looking credit-card number (<a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Luhn_algorithm">Luhn&#8217;s algorithm</a>, recently featured in a <a target="_blank" rel="nofollow" href="http://blogs.mathworks.com/videos/2013/09/16/luhn-checksum-implemented-in-matlab/">video tutorial</a> by Doug Hull). Of course, there are <a target="_blank" href="/articles/uitable-customization-report/#JIDE-Grids">dedicated JIDE controls</a> that do much of this already, but let&#8217;s not digress.<br />
In today&#8217;s example, we shall implement a simple input-validation function for a 5-digit zip code. When the input data is invalid, the editbox will be colored red and an appropriate message will appear next to the editbox. In addition, invalid (non-digit) characters shall be rejected with a beep sound.</p>
<h3 id="example">Zip-code validation example</h3>
<p>To illustrate the above, let&#8217;s use an example of a 5-digit zip-code entry validation. We start by creating an empty editbox with an associated message label next to it:</p>
<pre lang='matlab'>
figure('Color','w', 'Menubar','none');
hEditbox = uicontrol('Style','edit', 'Pos',[10,10,60,20], 'String','Matlab');  % start with an invalid string
hMessageLabel = uicontrol('Style','text', 'Pos',[80,10,200,20], 'horizontal','left', 'background','w', 'Foreground','red');
</pre>
<p>Next we get the underlying <code>jEditbox</code> reference and set its entry-validation callback function:</p>
<pre lang='matlab'>
jEditbox = findjobj(hEditbox);  % single-line editbox so there's need to drill-down the scroll-pane
set(jEditbox, 'KeyPressedCallback',{@editboxValidation,hMessageLabel});
</pre>
<p>Note how we pass the message-label&#8217;s handle as an extra input parameter to the callback function.<br />
Now we define the callback function <i>editboxValidation</i> and place it on the Matlab path (for example, by placing the following within <i>editboxValidation.m</i> in a folder that is already on your path):</p>
<pre lang='matlab'>
% editboxValidation - ensure that an editbox input is a valid 5-digit zip code
function editboxValidation(jEditbox, eventData, hMessageLabel)
    keyChar = eventData.getKeyChar;  % see note below about how we can trick Matlab here
    if ~alldigits(keyChar) && isprintable(keyChar)
        beep;
        fixedText = strrep(char(jEditbox.getText), keyChar, '');
        jEditbox.setText(fixedText);
    end
    updateAppearance(jEditbox, hMessageLabel);
end
% Check whether a string only contains digits
function flag = alldigits(str)
    flag = ~isnan(str2double(str));
end
% Check whether a character is printable
function flag = isprintable(keyChar)
    keyVal = double(keyChar);
    flag = ~isempty(keyVal) && keyVal > 31 && keyVal < 128;
end
% Update the GUI appearance based on the editbox text
function updateAppearance(jEditbox, hMessageLabel)
    currentText = char(jEditbox.getText);
    if isempty(currentText)
        set(hMessageLabel, 'String','Please enter a 5-digit zip-code')
        jEditbox.setBorder(javax.swing.border.LineBorder(java.awt.Color.red, 3, false));
    elseif ~alldigits(currentText)
        beep;
        set(hMessageLabel, 'String','Invalid zip: should only contain digits')
        jEditbox.setBorder(javax.swing.border.LineBorder(java.awt.Color.red, 3, false));
    elseif length(currentText) ~= 5
        set(hMessageLabel, 'String','Invalid zip: should have exactly 5 digits')
        jEditbox.setBorder(javax.swing.border.LineBorder(java.awt.Color.red, 3, false));
    else
        set(hMessageLabel, 'String','');
        jEditbox.setBorder(javax.swing.border.LineBorder(java.awt.Color.gray, 1, false));
    end
end
</pre>
<p>Finally, we call the validation function directly after creating our GUI, to let the user know that the zip-code needs to be entered:</p>
<pre lang='matlab'>
% Note how we trick Matlab by using eventData as a struct rather than a Java object
% (i.e., getKeyChar is set here to be a simple struct field, rather than a Java method)
eventData.getKeyChar = '';
editboxValidation(jEditbox,eventData,hMessageLabel)
</pre>
<p><center><figure style="width: 290px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Zip-code entry validation example" src="https://undocumentedmatlab.com/images/editbox_validation_animated.gif" title="Zip-code entry validation example" width="290" height="74" /><figcaption class="wp-caption-text">Zip-code entry validation example</figcaption></figure></center><br />
Naturally, this is a very simple example, and you can easily expand it for your needs. But it does show the basic components of any input validation: checking the new data, updating the control as appropriate, and modifying the appearance of the underlying control and of other associated controls.</p>
<h3 id="report">Available report &#8211; &#8220;Advanced Customizations of Matlab Uicontrols&#8221;</h3>
<p>Interested readers can find more information about these and other possible customizations in my report on &#8220;<i>Advanced Customizations of Matlab Uicontrols</i>&#8220;. This 90-page PDF report can be purchased <a target="_blank" rel="nofollow" href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&#038;currency_code=USD&#038;business=altmany@gmail.com&#038;amount=29&#038;item_name=Matlab+uicontrols+customization+report">here</a> ($29, please allow 24 hours for delivery by email). The report explains how to customize Matlab&#8217;s uicontrols in ways that are simply not possible using documented Matlab properties. This includes treatment of push buttons, toggle buttons, radio buttons, checkboxes, editboxes, listboxes, popup menus (aka combo-boxes/drop-downs), sliders, labels, and tooltips. Much of the information in the report is also available in hard-copy format in chapter 6 of my <a target="_blank" href="/matlab-java-book/">Matlab-Java programming book</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/editbox-data-input-validation">Editbox data input validation</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/ip-address-input-control" rel="bookmark" title="IP address input control">IP address input control </a> <small>A built-in JIDE control can be used in Matlab GUI for IP-address entry/display. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/smart-listbox-editbox-scrollbars" rel="bookmark" title="Smart listbox &amp; editbox scrollbars">Smart listbox &amp; editbox scrollbars </a> <small>Matlab listbox and multi-line editbox scrollbars can easily be made smarter, for improved appearance. ...</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>
<li><a href="https://undocumentedmatlab.com/articles/rich-matlab-editbox-contents" rel="bookmark" title="Rich Matlab editbox contents">Rich Matlab editbox contents </a> <small>The Matlab editbox uicontrol does not handle HTML contents as do other uicontrols. In this article I show how this limitation can be removed....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/editbox-data-input-validation/feed</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
	</channel>
</rss>
