<?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>Matt Whitaker &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/matt-whitaker/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 10 Mar 2010 07:18:58 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.3</generator>
	<item>
		<title>Matlab and the Event Dispatch Thread (EDT)</title>
		<link>https://undocumentedmatlab.com/articles/matlab-and-the-event-dispatch-thread-edt?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-and-the-event-dispatch-thread-edt</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-and-the-event-dispatch-thread-edt#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 10 Mar 2010 07:18:58 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<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[Semi-documented function]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[Matt Whitaker]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=1198</guid>

					<description><![CDATA[<p>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-and-the-event-dispatch-thread-edt">Matlab and the Event Dispatch Thread (EDT)</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/inactive-control-tooltips-event-chaining" rel="bookmark" title="Inactive Control Tooltips &amp; Event Chaining">Inactive Control Tooltips &amp; Event Chaining </a> <small>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setprompt-setting-matlab-desktop-prompt" rel="bookmark" title="setPrompt &#8211; Setting the Matlab Desktop prompt">setPrompt &#8211; Setting the Matlab Desktop prompt </a> <small>The Matlab Desktop's Command-Window prompt can easily be modified using some undocumented features...</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>
<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>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I welcome guest blogger Matt Whitaker, with the long awaited EDT article.</i></p>
<h3 id="EDT">Java Swing&#8217;s Event Dispatch Thread (EDT)<br /><i>or: why does my GUI foul up?</i></h3>
<p>Matlab for the most part is a single threaded environment. That is, all commands are executed sequentially along a single execution thread. The main exception to this are the Handle Graphics (GUI) components whose operations execute on the <a target="_blank" rel="nofollow" href="http://java.sun.com/docs/books/tutorial/uiswing/concurrency/dispatch.html">Java Event Dispatch Thread (EDT)</a>. EDT effects are reflected even in mundane Matlab GUI operations.<br />
If we execute the code below we will probably see nothing until the loop completes and the figure appears with the text label showing &#8216;10000&#8217;:</p>
<pre lang="matlab">
h = figure;
txt = uicontrol('Parent',h, 'Style','text', 'String','1');
for n = 1:10000
    set(txt,'String',int2str(n))
end %for
</pre>
<p>By adding a couple of <b><i>drawnow</i></b> commands we get the figure and text label to render and then we see the count progress to 10000.</p>
<pre lang="matlab">
h = figure;
txt = uicontrol('Parent',h, 'Style','text', 'String','1');
drawnow;
for n = 1:10000
    set(txt,'String',int2str(n));
    drawnow;
end %for
</pre>
<p>The <b><i>drawnow</i></b> function allows the EDT queue to be flushed and the pending graphics operations to be evaluated. This will also happen with <b><i>pause</i></b> and several other commands.<br />
If we want to use Swing (or AWT) components in our user interfaces we need to take this multi-threaded environment into account. The Swing toolkit designers decided to make all the Swing components thread <b><u>un</u></b>-safe in order to decrease their complexity. As a consequence, all access to Swing components should be done from the event dispatch thread (EDT), to ensure the operations are executed sequentially, at the exact order in which they were dispatched. Any action on a Swing component done on another thread (Matlab&#8217;s main processing thread in our case) risks a race-condition or deadlock with the EDT, which could (and often does) result in weird, non-deterministic and non-repetitive behavior – all of which should be avoided in any application which should behave in a precisely deterministic manner.<br />
In Java, the usual pattern to accomplish EDT dispatching is to create a <a target="_blank" rel="nofollow" href="http://java.sun.com/javase/6/docs/api/java/lang/Runnable.html">Runnable</a> object, encapsulate the GUI code in the <i>run</i> method of the Runnable object, then pass the Runnable object to the static <a target="_blank" rel="nofollow" href="http://java.sun.com/javase/6/docs/api/java/awt/EventQueue.html#invokeLater(java.lang.Runnable)">EventQueue.invokeLater</a> (or <a target="_blank" rel="nofollow" href="http://java.sun.com/javase/6/docs/api/java/awt/EventQueue.html#invokeAndWait(java.lang.Runnable)">EventQueue.invokeAndWait</a> if we need to block operations to get a return value) method.</p>
<pre lang="java">
Runnable runnable = new Runnable()
{
    public void run()
    {
        //GUI Code here
    }
}
EventQueue.invokeLater(runnable);
</pre>
<p>There are several functions in Matlab that implement this programming pattern for us: <b><i>javaObjectEDT</i></b>, <b><i>javaMethodEDT</i></b>, <b><i>awtinvoke</i></b>, <b><i>awtcreate</i></b> and <b><i>javacomponent</i></b>. <b><i>JavaMethodEDT</i></b> and <b><i>javaObjectEDT</i></b> were introduced in version R2008b (7.7) and are <a target="_blank" rel="nofollow" href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/javaobjectedt.html">minimally and only partially documented</a> although they have reasonably complete help comments. The other three are semi-documented (meaning they are unsupported but if you edit or type their m-file you&#8217;ll see a fairly detailed help section), and although there is some overlap in their functionality they are still available.</p>
<h3 id="javaObjectEDT">javaObjectEDT and javaMethodEDT</h3>
<p><b><i>javaObjectEDT</i></b> is the the preferred method since R2008b of creating swing components to be used on the EDT. An object created with <b><i>javaObjectEDT</i></b> will have all of its subsequent method calls run on the EDT. This is termed <i>Auto Delegation</i>. Auto-delegation greatly simplifies and increases the readability of code. Note that objects created as a result of method calls may not be implemented on the EDT.<br />
If you have an existing Java object, you can pass it to <b><i>javaObjectEDT</i></b> at any time &#8211; all its subsequent calls will then onward run on the EDT. Note that this useful functionality is an under-documented <b><i>javaObjectEDT</i></b> feature: it is not mentioned in the main help section but only implied from the example.</p>
<pre lang="matlab">
% Create a button on the EDT
btn = javaObjectEDT('javax.swing.JButton');
% this will run on EDT since btn was javaObjectEDT-created
btn.setText('Button');
% Create a button NOT on the EDT
btn2 = javax.swing.JButton;
% Dangerous! call will run on main Matlab thread
btn2.setText('Button2');
% modify btn2 so its methods will start running on the EDT
javaObjectEDT(btn2);
btn2.setText('Button2');
</pre>
<p>The following example shows the use of <b><i>javaObjectEDT</i></b> and <b><i>javaMethodEDT</i></b> in a more complex situation using a JTable:</p>
<pre lang="matlab">
function tableExample
hFig = figure;
drawnow; %need to get figure rendered
%use Yair's createTable to add a javax.swing.JTable
%http://www.mathworks.com/matlabcentral/fileexchange/14225-java-based-data-table
%wrap ceateTable in javaObjectEDT to put the ensuing method calls on the EDT
f = java.awt.Font(java.lang.String('Dialog'),java.awt.Font.PLAIN,14);
headers = {'Selected','File','Analysis Routine','Task Status'};
tbl = javaObjectEDT(createTable(hFig,headers,[],false,'Font',f));
%set column 1 to use check boxes and set up a change callback
tbl.setCheckBoxEditor(1);
jtable = javaObjectEDT(tbl.getTable); %get the underlying Java Table. IMPORTANT: we need to put jtable on the EDT
columnModel = javaObjectEDT(jtable.getColumnModel); %now we can now do direct calls safely on jtable
selectColumn = javaObjectEDT(columnModel.getColumn(0));
selectColumnCellEditor = selectColumn.getCellEditor;
chk = javaMethodEDT('getComponent',selectColumnCellEditor);
set(chk,'ItemStateChangedCallback',@chkChange_Callback);
%make column three a combo drop down
analysisTable = {'Analysis1';'Analysis2';'Analysis3'};
cb = javaObjectEDT('com.mathworks.mwswing.MJComboBox',analysisTable);
cb.setEditable(false);
cb.setFont(f);
set(cb,'ItemStateChangedCallback',@cbChange_Callback);
editor = javaObjectEDT('javax.swing.DefaultCellEditor',cb);
analysisColumn = javaObjectEDT(columnModel.getColumn(2));
analysisColumn.setCellEditor(editor);
%set some column with restrictions
selectColumn.setMaxWidth(100);
analysisColumn.setPreferredWidth(300);
%set the data
SELECTED = java.awt.event.ItemEvent.SELECTED;
tbl.setData({false,'file1','Analysis2','Analysis2';...
             true,'file2','Analysis3','Analysis3'});
drawnow;
    function cbChange_Callback(src,ev) %#ok
        jRow = jtable.getSelectedRow;
        stateChange = javaMethodEDT('getStateChange',ev);
        if stateChange == SELECTED
            newData = javaMethodEDT('getItem',ev);
            model = jtable.getModel;
            javaMethodEDT('setValueAt',model,newData,jRow,3);
        end %if
    end %cbChange
    function chkChange_Callback(src,ev) %#ok
        chkBox = javaMethodEDT('getItem',ev);
        if logical(javaMethodEDT('isSelected',chkBox))
            beep; %put useful code here
        else
            beep;
            pause(0.1)
            beep; %put useful code here
        end %if
    end %chkChange_Callback
end %tableExample
</pre>
<p>If you are running Matlab R2008a or later, <b><i>javacomponent</i></b> uses the <b><i>javaObjectEDT</i></b> function to create the returned objects so you do not have to do anything further to these objects to have their calls dispatched on the EDT. Users need to take care that objects added directly to the components created by <b><i>javacomponent</i></b> are on the EDT as well as specialized sub-components (e.g. CellRenderers and CellEditors). The overhead of calling <b><i>javaMethodEDT</i></b> is fairly small so if in doubt, use it.<br />
<b><i>javaObjectEDT</i></b> and its kin first appeared in R2008a, although they only became supported in R2008b. Unfortunately, using them on R2008a sometimes causes hangs and all sorts of other mis-behaviors. This problem was fixed in the R2008b release, when <b><i>javaObjectEDT</i></b> became a fully-supported function. The problem with using <b><i>javaObjectEDT</i></b> in our application is that if it ever runs on an R2008a platform it might hang! (on Matlab release R2007b and earlier we will get an informative message saying that the <b><i>javaObjectEDT</i></b> function does not exist)<br />
For this reason, I am using the following method in my projects:</p>
<pre lang="matlab">
function result = javaObjEDT(varargin)
%Placeholder of Matlab's buggy javaObjectEDT function on R2008a
% Programmed by Yair M. Altman: altmany(at)gmail.com
% $Revision: 1.2 $  $Date: 2009/01/25 11:31:08 $
  try
      try
          result = varargin{1};
      catch
          result = [];
      end
      v = version;
      if str2double(v(1:3)) > 7.6
          result = builtin('javaObjectEDT',varargin{:});
      end
  catch
      % never mind
  end
end
</pre>
<p>Note that <b><i>javaMethodEDT</i></b> has the method name as its first input argument, and the object name or reference as its second arg. This is inconsistent with many other Matlab/Java functions, which normally accept the target object as the first argument (compare: <b><i>invoke</i></b>, <b><i>awtinvoke</i></b>, <b><i>notify</i></b> etc.). It also means that we cannot use the familiar <i>obj.javaMethodEDT(methodName)</i> format.<br />
One final note: when <b><i>javaObjectEDT</i></b> and <b><i>javaMethodEDT</i></b> first appeared in R2008a, they were complemented by the <b><i>javaObjectMT</i></b> and <b><i>javaMethodMT</i></b> functions, which create and delegate Java objects on the main Matlab computational thread. Their internal documentation says that there are cases when execution must occur on the MT rather than EDT, although I am personally not aware of any such case.</p>
<h3 id="awtcreate">awtcreate and awtinvoke</h3>
<p>For users with versions prior to R2008b the user must use the <b><i>awtcreate</i></b> function to create objects on the EDT. One huge disadvantage of this older function is that if you have to pass java objects in the parameter list you must use the very cumbersome <a target="_blank" rel="nofollow" href="http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/types.html#wp276">JNI style notation</a>. For example, for the simple task of setting a button label, one has to use:</p>
<pre lang="matlab">
btn = awtcreate('javax.swing.JButton');
awtinvoke(btn,'setText(Ljava/lang/String;)','click me')
</pre>
<p>The other disadvantage is that creating the object using <b><i>awtcreate</i></b> does not ensure that its subsequent method calls will be executed on the EDT. The <b><i>awtinvoke</i></b> function must be used for each call.<br />
Also, both <b><i>awtcreate</i></b> and <b><i>awtinvoke</i></b> have some limitations due to bugs in the private <b><i>parseJavaSignature</i></b> function (for example, invoking methods which accept a java.lang.Object) which forces one to use the direct call to the method, using the main Matlab thread. This can result in the undesired effects described above. In this situation the best workaround is to call <i><b>pause</b>(0.01)</i> to allow the event queue to clear.<br />
Versions of <b><i>javacomponent</i></b> earlier than R2008a use <b><i>awtcreate</i></b> and objects created by these versions must have their subsequent methods called by <b><i>awtinvoke</i></b> to be used on the EDT.<br />
A very rare <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/156388">CSSM thread</a> discusses the usage of <b><i>awtcreate</i></b> and <b><i>awtinvoke</i></b> with some very interesting remarks by MathWorks personnel.<br />
There is an interesting option in <b><i>awtinvoke</i></b> that was not carried over into the newer <b><i>javaMethodEDT</i></b>. This option allows the user to pass a function handle in the argument list along with its parameters. This option creates an undocumented com.mathworks.jmi.Callback object that has a delayed callback. The delayed callback is dispatched on the EDT so that it will be called once the java method used in <b><i>awtinvoke</i></b> is finished. Note that the actual function will still execute on the main Matlab thread the delayed callback will just control when it is called. However this may be useful at times. It is possible to put this functionality into a separate function we can call to delay execution until the event queue is cleared.</p>
<pre lang="matlab">
%CALLBACKONEDTQUEUE will place a callback on the EDT to asynchronously
%run a function.
%CALLBBACKONEDTQUEUE(FCN) will run function handle FCN once all previous
%methods dispatched to the EDT have completed.
%CALLBBACKONEDTQUEUE(FCN,ARG1,ARG2,...) ill run function handle FCN with
%arguments ARG1,ARG2...once all previous methods dispatched to the EDT
%have completed.
%Note that the function is still executing on the main Matlab thread. This
%function just delays when it will be called.
function callbackOnEDTQueue(varargin)
    validateattributes(varargin{1},{'function_handle'},{});
    callbackObj = handle(com.mathworks.jmi.Callback,'callbackProperties');
    set(callbackObj,'delayedCallback',{@cbEval,varargin(:)});
    callbackObj.postCallback;
    function cbEval(src,evt,args) %#ok
        feval(args{:});
    end %cbEval
end %callbackOnEDTQueue
</pre>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-and-the-event-dispatch-thread-edt">Matlab and the Event Dispatch Thread (EDT)</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/inactive-control-tooltips-event-chaining" rel="bookmark" title="Inactive Control Tooltips &amp; Event Chaining">Inactive Control Tooltips &amp; Event Chaining </a> <small>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setprompt-setting-matlab-desktop-prompt" rel="bookmark" title="setPrompt &#8211; Setting the Matlab Desktop prompt">setPrompt &#8211; Setting the Matlab Desktop prompt </a> <small>The Matlab Desktop's Command-Window prompt can easily be modified using some undocumented features...</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>
<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>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-and-the-event-dispatch-thread-edt/feed</wfw:commentRss>
			<slash:comments>40</slash:comments>
		
		
			</item>
		<item>
		<title>Inactive Control Tooltips &#038; Event Chaining</title>
		<link>https://undocumentedmatlab.com/articles/inactive-control-tooltips-event-chaining?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=inactive-control-tooltips-event-chaining</link>
					<comments>https://undocumentedmatlab.com/articles/inactive-control-tooltips-event-chaining#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 24 Feb 2010 22:34:46 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Listeners]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[Listener]]></category>
		<category><![CDATA[Matt Whitaker]]></category>
		<category><![CDATA[uicontrol]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=1153</guid>

					<description><![CDATA[<p>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/inactive-control-tooltips-event-chaining">Inactive Control Tooltips &amp; Event Chaining</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-and-the-event-dispatch-thread-edt" rel="bookmark" title="Matlab and the Event Dispatch Thread (EDT)">Matlab and the Event Dispatch Thread (EDT) </a> <small>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....</small></li>
<li><a href="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/spicing-up-matlab-uicontrol-tooltips" rel="bookmark" title="Spicing up Matlab uicontrol tooltips">Spicing up Matlab uicontrol tooltips </a> <small>Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/multi-line-tooltips" rel="bookmark" title="Multi-line tooltips">Multi-line tooltips </a> <small>Multi-line tooltips are very easy to set up, once you know your way around a few undocumented hiccups....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again, I welcome guest blogger Matt Whitaker, who continues his series of articles.</i><br />
In my last post I explored some <a target="_blank" href="/articles/additional-uicontrol-tooltip-hacks/">tips on tooltips</a>. One of these tips involved displaying tooltips on disabled uicontrols. I explained that displaying tooltips on inactive controls is problematic since Matlab appears to intercept mouse events to these inactive controls, so even setting the tooltip on the underlying Java object will not work: The java object appears not to receive the mouse-hover event and therefore does not &#8220;know&#8221; that it&#8217;s time to display the tooltip.<br />
When Yair and I deliberated this issue, he pointed me to his <a target="_blank" href="/articles/spicing-up-matlab-uicontrol-tooltips/#comment-1173">comment on a previous article</a> showing an undocumented Java technique (Java also has some&#8230;) for forcing a tooltip to appear using the <b>ActionMap</b> of the uicontrol&#8217;s underlying Java object to get at a <i>postTip</i> action. We discussed using a <b>WindowButtonMotionFcn</b> callback to see if the mouse was above the inactive control, then triggering the forced tooltip display. Yair then went on to remind me and I quote: <i>&#8220;you&#8217;ll need to chain existing <b>WindowButtonMotionFcn</b> callbacks and take into account ModeManagers that override them.&#8221;</i><br />
Frankly, having written code previously that handles callback chaining, I would rather poke myself in the eye with a fork!<br />
The Image Processing Toolbox has the nice pair of <b><i>iptaddcallback</i></b> and <b><i>iptremovecallback</i></b> functions that largely handle these issues. But  for general Matlab, there seemed to be no alternative until I remembered that events trigger callbacks. I decided to use a listener for the <i>WindowButtonMotion</i> event to detect the mouse motion. <a target="_blank" href="/articles/continuous-slider-callback/#Event_Listener">Event listeners were briefly explained two weeks ago</a> and deserve a dedicated future article. The advantage of using an event listener is that we don&#8217;t disturb any existing <b>WindowButtonMotionFcn</b> callback. We still need to be somewhat careful that our listeners don&#8217;t do conflicting things, but it&#8217;s a lot easier than trying to manage everything through the single <b>WindowButtonMotionFcn</b>.<br />
A demonstration of this appears below with some comments following (note that this code uses the <a target="_blank" href="/articles/findjobj-find-underlying-java-object/"><b><i>FindJObj</i></b> utility</a>):</p>
<pre lang="matlab">
function inactiveBtnToolTip
  %Illustrates how to make a tooltip appear on an inactive control
  h = figure('WindowButtonMotionFcn',@windowMotion,'Pos',[400,400,200,200]);
  col = get(h,'color');
  lbl = uicontrol('Style','text', 'Pos',[10,160,120,20], ...
                  'Background',col, 'HorizontalAlignment','left');
  btn = uicontrol('Parent',h, 'String','Button', ...
                  'Enable','inactive', 'Pos',[10,40,60,20]);
  uicontrol('Style','check', 'Parent',h, 'String','Enable button tooltip', ...
            'Callback',@chkTooltipEnable, 'Value',1, ...
            'Pos',[10,80,180,20], 'Background',col);
  drawnow;
  %create the tooltip and postTip action
  jBtn = findjobj(btn);
  import java.awt.event.ActionEvent;
  javaMethodEDT('setToolTipText',jBtn,'This button is inactive');
  actionMap = javaMethodEDT('getActionMap',jBtn);
  action = javaMethodEDT('get',actionMap,'postTip');
  actionEvent = ActionEvent(jBtn, ActionEvent.ACTION_PERFORMED, 'postTip');
  %get the extents plus 2 pixels of the control to compare to the mouse position
  btnPos = getpixelposition(btn)+[-2,-2,4,4]; %give a little band around the control
  left = btnPos(1);
  right = sum(btnPos([1,3]));
  btm = btnPos(2);
  top =  sum(btnPos([2,4]));
  % add a listener on mouse movement events
  tm = javax.swing.ToolTipManager.sharedInstance; %tooltip manager
  pointListener = handle.listener(h,'WindowButtonMotionEvent',@figMouseMove);
  %inControl is a flag to prevent multiple triggers of the postTip action
  %while mouse remains in the button
  inControl = false;
  function figMouseMove(src,evtData) %#ok
    %get the current point
    cPoint = evtData.CurrentPoint;
    if cPoint(1) >= left && cPoint(1) <= right &#038;&#038;...
       cPoint(2) >= btm  && cPoint(2) <= top
      if ~inControl %we just entered
        inControl = true;
        action.actionPerformed(actionEvent); %show the tooltip
      end %if
    else
      if inControl %we just existed
        inControl = false;
        %toggle to make it disappear when leaving button
        javaMethodEDT('setEnabled',tm,false);
        javaMethodEDT('setEnabled',tm,true);
      end %if
    end %if
  end %gpMouseMove
  function windowMotion(varargin)
    %illustrate that we can still do a regular window button motion callback
    set(lbl,'String',sprintf('Mouse position: %d, %d',get(h,'CurrentPoint')));
    drawnow;
  end %windowMotion
  function chkTooltipEnable(src,varargin)
    if get(src,'Value')
      set(pointListener,'Enable','on');
    else
      set(pointListener,'Enable','off');
    end %if
  end %chkTooltipEnable
end %inactiveBtnToolTip
</pre>
<p><center><figure style="width: 208px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" alt="Tooltip on an inactive button" src="https://undocumentedmatlab.com/images/tooltip4.png" title="Tooltip on an inactive button" width="208" height="255" /><figcaption class="wp-caption-text">Tooltip on an inactive button</figcaption></figure></center><br />
Comments on the code:</p>
<ol>
<li>The code illustrates that we can successfully add an additional listener to listen for mouse motion events while still carrying out the original <b>WindowButtonMotionFcn</b> callback. This makes chaining callbacks much easier.</li>
<li>The <b><i>handle.listener</i></b> object has an <b>Enable</b> property that we can use to temporarily turn the listener on and off. This can be seen in the <i>chkTooltipEnable()</i> callback for the check box in the code above. If we wanted to permanently remove the listener we would simply use <i><b>delete</b>(pointListener)</i>. Note that <b><i>addlistener</i></b> adds a hidden property to the object being listened to, so that the listener is tied to the object's lifecycle. If you create a listener directly using <b><i>handle.listener</i></b> you are responsible for it's disposition. Unfortunately, <b><i>addlistener</i></b> fails for HG handles on pre-R2009 Matlab releases, so we use <b><i>handle.listener</i></b> directly.</li>
<li>The code illustrates a good practice when tracking rapidly firing events like mouse movement of handling reentry into the callback while it is still processing a previous callback. Here we use a flag called inControl to prevent the <i>postTip</i> action being continuously fired while the mouse remains in the control.</li>
<li>I was unable to determine if there is any corresponding action for the <i>postTip</i> to dismiss tips so I resorted to using the ToolTipManager to toggle its own <b>Enable</b> property to cleanly hide the tooltip as the mouse leaves the control.</li>
</ol>
<p>Each Matlab callback has an associated event with it. Some of the ones that might be immediately useful at the figure-level are <b>WindowButtonDown</b>, <b>WindowButtonUp</b>, <b>WindowKeyPress</b>, and <b>WindowKeyRelease</b>. They can all be accessed through <b><i>handle.listener</i></b> or <b><i>addlistener</i></b> as in the code above.<br />
Unfortunately, events do not always have names that directly correspond to the callback names. In order to see the list of available events for a particular Matlab object, use the following code, which relies on another undocumented function - <b><i>classhandle</i></b>. Here we list the events for <b><i>gcf</i></b>:</p>
<pre lang="matlab">
>> get(get(classhandle(handle(gcf)),'Events'),'Name')
ans =
    'SerializeEvent'
    'FigureUpdateEvent'
    'ResizeEvent'
    'WindowKeyReleaseEvent'
    'WindowKeyPressEvent'
    'WindowButtonUpEvent'
    'WindowButtonDownEvent'
    'WindowButtonMotionEvent'
    'WindowPostChangeEvent'
    'WindowPreChangeEvent'
</pre>
<p>Note that I have made extensive use of the <b><i>javaMethodEDT</b></i> function to execute Java methods that affect swing components on Swing's Event Dispatch Thread. I plan to write about this and related functions in my next article.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/inactive-control-tooltips-event-chaining">Inactive Control Tooltips &amp; Event Chaining</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-and-the-event-dispatch-thread-edt" rel="bookmark" title="Matlab and the Event Dispatch Thread (EDT)">Matlab and the Event Dispatch Thread (EDT) </a> <small>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....</small></li>
<li><a href="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/spicing-up-matlab-uicontrol-tooltips" rel="bookmark" title="Spicing up Matlab uicontrol tooltips">Spicing up Matlab uicontrol tooltips </a> <small>Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/multi-line-tooltips" rel="bookmark" title="Multi-line tooltips">Multi-line tooltips </a> <small>Multi-line tooltips are very easy to set up, once you know your way around a few undocumented hiccups....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/inactive-control-tooltips-event-chaining/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Additional uicontrol tooltip hacks</title>
		<link>https://undocumentedmatlab.com/articles/additional-uicontrol-tooltip-hacks?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=additional-uicontrol-tooltip-hacks</link>
					<comments>https://undocumentedmatlab.com/articles/additional-uicontrol-tooltip-hacks#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 17 Feb 2010 17:25:52 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<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[FindJObj]]></category>
		<category><![CDATA[Matt Whitaker]]></category>
		<category><![CDATA[uicontrol]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=1114</guid>

					<description><![CDATA[<p>Matlab's uicontrol tooltips have several limitations that can be overcome using the control's underlying Java object.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/additional-uicontrol-tooltip-hacks">Additional uicontrol tooltip 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/spicing-up-matlab-uicontrol-tooltips" rel="bookmark" title="Spicing up Matlab uicontrol tooltips">Spicing up Matlab uicontrol tooltips </a> <small>Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/listbox-selection-hacks" rel="bookmark" title="Listbox selection hacks">Listbox selection hacks </a> <small>Matlab listbox selection can be customized in a variety of undocumented ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-line-position-in-edit-box-uicontrol" rel="bookmark" title="Setting line position in an edit-box uicontrol">Setting line position in an edit-box uicontrol </a> <small>Matlab uicontrols have many useful features that are only available via Java. Here's how to access them....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/inactive-control-tooltips-event-chaining" rel="bookmark" title="Inactive Control Tooltips &amp; Event Chaining">Inactive Control Tooltips &amp; Event Chaining </a> <small>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I&#8217;d like to welcome guest blogger Matthew Whitaker. Today Matt will discuss uicontrol tooltips hacks as the first of several posts that follow a logical thread culminating in the long promised article on the EDT.</i><br />
<br />
A while back Yair wrote a cool article, <a target="_blank" href="/articles/spicing-up-matlab-uicontrol-tooltips/">Spicing up Matlab uicontrol tooltips</a>, describing use of HTML formatting and images in <b><i>uicontrol</i></b> tooltips. I want to share some limitations I&#8217;ve seen with tooltips and their solution using the Matlab control&#8217;s underlying Java object.</p>
<h3 id="disabled-controls">Situation 1: Displaying a tooltip on disabled controls</h3>
<p>One issue with the stock Matlab <b><i>uicontrol</i></b> tooltips is that if you turn the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/uicontrol_props.html#bqxoiky">uicontrol&#8217;s <b>Enable</b> property</a> to &#8216;inactive&#8217; or &#8216;off&#8217;, its tooltip no longer displays. This is the behavior that we normally want, but occasionally we wish to display a tooltip on a disabled control, for example, to explain why the control is disabled.<br />
You can use the <a target="_blank" href="/articles/findjobj-find-underlying-java-object/"><b><i>findjobj</i></b> utility</a> to find the Java handle for the <b><i>uicontrol</i></b>. This handle can then be used to set the tooltip text. The tooltip will display if you disable the control using its Java handle&#8217;s <b>Enabled</b> property rather than the Matlab handle&#8217;s <b>Enable</b> property:</p>
<pre lang="matlab">
hButton = uicontrol('String','Button');
drawnow;
jButton= findjobj(hButton);
set(jButton,'Enabled',false);
set(jButton,'ToolTipText','This is disabled for a reason');
</pre>
<p>As customary for Java objects, its properties can also be set using their corresponding accessor methods:</p>
<pre lang="matlab">
javaMethodEDT('setEnabled',jButton,false);
javaMethodEDT('setToolTipText',jButton,'Button is disabled for a reason');
</pre>
<p><center><figure style="width: 252px" class="wp-caption aligncenter"><img decoding="async" alt="tooltip on a disabled uicontrol" src="https://undocumentedmatlab.com/images/tooltip1.png" title="tooltip on a disabled uicontrol" width="252" height="46" /><figcaption class="wp-caption-text">tooltip on a disabled uicontrol</figcaption></figure></center><br />
Unfortunately, this hack does not work for &#8216;inactive&#8217; controls. There is no direct Java analogy for inactive controls &#8211; it&#8217;s a Matlab extension. It appears that Matlab somehow intercepts the mouse events associated with inactive controls. My next post will show how event callback can be used to display tooltips for inactive controls.<br />
As an alternative for inactive edit-box controls, we can simulate the inactive behavior by setting the Java object&#8217;s <b>Editable</b> property (or by using its <i>setEditable()</i> accessor method), then setting the tooltip. Note that the extremely-useful Java <b>Editable</b> property is unavailable in the Matlab handle, for some inexplicable reason:</p>
<pre lang="matlab">
hEditbox = uicontrol('String','Edit Text','Style','edit');
drawnow;
jEditbox = findjobj(hEditbox);
set(jEditbox,'Editable',false);
set(jEditbox,'ToolTipText','Text is inactive for a reason');
</pre>
<p><center><figure style="width: 232px" class="wp-caption aligncenter"><img decoding="async" alt="tooltip on a non-editable editbox" src="https://undocumentedmatlab.com/images/tooltip2.png" title="tooltip on a non-editable editbox" width="232" height="50" /><figcaption class="wp-caption-text">tooltip on a non-editable editbox</figcaption></figure></center></p>
<h3 id="truncated_text">Situation 2: Displaying a tooltip on truncated text</h3>
<p>If we want to conditionally display a tooltip for an editbox <b><i>uicontrol</i></b> when the text exceeds the control&#8217;s width, we can use the <b>TipWhenTruncatedEnabled</b> property (or its corresponding <i>setTipWhenTruncatedEnabled()</i> method). This will display a tooltip with the editbox contents if the string is shown truncated. This saves the user having to scroll through the control to see its contents. I often use this for edit controls that may contain long path names:</p>
<pre lang="matlab">
hEditbox(1) = uicontrol('Style','edit','Units','norm','Pos',[0.1,0.8,0.4,0.05], 'String','Too Short');
hEditbox(2) = uicontrol('Style','edit','Units','norm','Pos',[0.1,0.7,0.2,0.05], 'String','Long Enough to Display a Tool Tip');
drawnow;
jEditbox1 = findjobj(hEditbox(1));
jEditbox2 = findjobj(hEditbox(2));
set(jEditbox1,'TipWhenTruncatedEnabled',true);  % property-based alternative
javaMethod('setTipWhenTruncatedEnabled',jEditbox2,true);  % method-based alternative
</pre>
<p><center><figure style="width: 250px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="TipWhenTruncatedEnabled tooltip" src="https://undocumentedmatlab.com/images/tooltip3.png" title="TipWhenTruncatedEnabled tooltip" width="250" height="100" /><figcaption class="wp-caption-text">TipWhenTruncatedEnabled tooltip</figcaption></figure></center><br />
The <b>TipWhenTruncatedEnabled</b> property property is also available for multi-line editboxes, but has (obviously) no effect when scrollbars are present. Also note that setting the <b>TipWhenTruncatedEnabled</b> property to true overrides any previous tooltip that might have been set for the editbox.<br />
Finally, note that the <b>TipWhenTruncatedEnabled</b> property can also be set for the editbox component of popup-menu (aka drop-down) controls, <u>after</u> they have been set to be editable using their Java <b>Editable</b> property (note that both properties are false by default for Matlab uicontrols). In the following screenshot, the drop-down&#8217;s editbox component contained an HTML snippet, that is shown unformatted within the edit-box and HTML-formatted in the de-truncated tooltip:<br />
<center><figure style="width: 115px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="de-truncated HTML-format tooltip" src="https://undocumentedmatlab.com/images/popup_TipWhenTruncatedEnabled2.png" title="de-truncated HTML-format tooltip" width="115" height="72" /><figcaption class="wp-caption-text">de-truncated HTML-format tooltip</figcaption></figure></center></p>
<h3 id="tooltip_timing">Situation 3: Controlling tooltip timing</h3>
<p>As you have probably noticed, there is a slight delay between the time your mouse enters the control and when the tooltip actually appears. If you display a tooltip over a control for sufficiently long the tooltip will then disappear. Sometimes the default delays are too slow or fast for your application. These times can be controlled through the <a target="_blank" rel="nofollow" href="http://java.sun.com/javase/6/docs/api/javax/swing/ToolTipManager.html">javax.swing.ToolTipManager</a>. The ToolTipManager sets these parameters globally (including for your Matlab desktop components), but they are not persistent between sessions.<br />
Some examples using the ToolTipManager:</p>
<pre lang="matlab">
btn = uicontrol('String','Button','Tooltip','This is a button.','Pos',[100,100,75,25]);
txt = uicontrol('Style','edit','String','Edit Text','Tooltip','This is editable text','Pos',[100,50,75,25]);
tm = javax.swing.ToolTipManager.sharedInstance; %static method to get ToolTipManager object
initialDelay = javaMethodEDT('getInitialDelay',tm); %get the delay before display in milliseconds (=750 on my system)
javaMethodEDT('setInitialDelay',tm,0); %set tooltips to appear immediately
dismissDelay = javaMethodEDT('getDismissDelay',tm); %get the delay before the tooltip disappears (=10000 (10 sec) on my system)
javaMethodEDT('setDismissDelay',tm,2000); %set the dismiss delay to 2 seconds
javaMethodEDT('setEnabled',tm,false); %turns off all tooltips in system (including the Matlab desktop)
javaMethodEDT('setEnabled',tm,true);
javaMethodEDT('setInitialDelay',tm,initialDelay);
javaMethodEDT('setDismissDelay',tm,dismissDelay);
</pre>
<p>Note that I have made extensive use of the undocumented built-in <b><i>javaMethodEDT</i></b> function to execute Java methods that affect Swing components on the Swing Event Dispatch Thread (EDT). I plan to write about EDT following my next post on event callback chaining.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/additional-uicontrol-tooltip-hacks">Additional uicontrol tooltip 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/spicing-up-matlab-uicontrol-tooltips" rel="bookmark" title="Spicing up Matlab uicontrol tooltips">Spicing up Matlab uicontrol tooltips </a> <small>Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/listbox-selection-hacks" rel="bookmark" title="Listbox selection hacks">Listbox selection hacks </a> <small>Matlab listbox selection can be customized in a variety of undocumented ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-line-position-in-edit-box-uicontrol" rel="bookmark" title="Setting line position in an edit-box uicontrol">Setting line position in an edit-box uicontrol </a> <small>Matlab uicontrols have many useful features that are only available via Java. Here's how to access them....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/inactive-control-tooltips-event-chaining" rel="bookmark" title="Inactive Control Tooltips &amp; Event Chaining">Inactive Control Tooltips &amp; Event Chaining </a> <small>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/additional-uicontrol-tooltip-hacks/feed</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>Solving a MATLAB bug by subclassing</title>
		<link>https://undocumentedmatlab.com/articles/solving-a-matlab-bug-by-subclassing?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=solving-a-matlab-bug-by-subclassing</link>
					<comments>https://undocumentedmatlab.com/articles/solving-a-matlab-bug-by-subclassing#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 07 Feb 2010 23:57:25 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Toolbox]]></category>
		<category><![CDATA[Matt Whitaker]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Undocumented property]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=1110</guid>

					<description><![CDATA[<p>Matlab's Image Processing Toolbox's impoint function contains an annoying bug that can be fixed using some undocumented properties.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/solving-a-matlab-bug-by-subclassing">Solving a MATLAB bug by subclassing</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/solving-a-matlab-mcos-bug" rel="bookmark" title="Solving a Matlab MCOS bug">Solving a Matlab MCOS bug </a> <small>Matlab has a bug with handling multi-element class-access constructs. This post explains the problem and solution. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/solving-a-matlab-hang-problem" rel="bookmark" title="Solving a Matlab hang problem">Solving a Matlab hang problem </a> <small>A very common Matlab hang is apparently due to an internal timing problem that can easily be solved. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/solving-an-mput-ftp-hang-problem" rel="bookmark" title="Solving an mput (FTP) hang problem">Solving an mput (FTP) hang problem </a> <small>Matlab may hang when using passive FTP commands such as mput and dir. A simple workaround is available to fix this. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/simple-gui-tabs-for-advanced-matlab-trading-app" rel="bookmark" title="Simple GUI Tabs for Advanced Matlab Trading App">Simple GUI Tabs for Advanced Matlab Trading App </a> <small>A new File Exchange utility enables to easily design GUI tabs using Matlab's GUIDE...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I would like to welcome guest blogger <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/author/94021">Matthew Whitaker</a>. Many of Matt&#8217;s CSSM submissions offer important insight of internal Matlab functionality. As shall be seen by today&#8217;s article and some future submissions, Matt has plenty to share vis-a-vis Matlab&#8217;s undocumented functionality.</i><br />
In my day-to-day work I make extensive use of MATLAB&#8217;s <a target="_blank" rel="nofollow" href="http://www.mathworks.com/products/image/">Image Processing Toolbox</a> (IPT). One area of the toolbox that has seen considerable change over the last few releases has been the development of a set of <a target="_blank" rel="nofollow" href="http://www.mathworks.com/access/helpdesk/help/toolbox/images/f17-6011.html">modular tools</a> to aid in GUI design for image processing applications. In this article, I examine a bug in one of those tools to illustrate how we can use the power of subclassing these objects (using an undocumented property) to design a simple and effective workaround.</p>
<h3>The problem</h3>
<p>The problem arose as I was refactoring some code that was written in R2006b to R2009b. The code in question uses the <b><i>impoint</i></b> tool on an image along with an associated <b><i>text</i></b> object that moves with the point to display information as it is dragged around the image. At the time of the R2006b release the <b><i>impoint</i></b> tool was written as an API. In R2006b the call to <b><i>impoint</i></b> returns a handle to an <a target="_blank" rel="nofollow" href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/hggroup.html"><b><i>hggroup</i></b></a> containing a structure of function handles in its application data under the tag &#8216;API&#8217;. This programming pattern was common before the advent of the new class syntax in MATLAB version 7.6 (R2008a).<br />
Here is an example of how <b><i>impoint</i></b> would be used in R2006b:</p>
<pre lang="matlab">
function impointBehavior_R2006b
%IMPOINTBEHAVIOR_R2006B shows how impoint would be used in R2006b
%Note: RUN UNDER R2006B (will run under R2009b but actually uses
%classdef impoint so it will show the same issue)
  % Display the image in a figure window
  figure;  imshow('rice.png');
  % In R2006b calling impoint returns the hggroup handle
  h = impoint(gca,100,200);
  % In 2006b iptgetapi returns a structure of function handles
  api = iptgetapi(h);
  % Add a new position callback to set the text string
  api.addNewPositionCallback(@newPos_Callback);
  % Construct boundary constraint function so we can't go outside the axes
  fcn = makeConstrainToRectFcn('impoint',get(gca,'XLim'),get(gca,'YLim'));
  api.setDragConstraintFcn(fcn);
  % Fire callback so we get initial text
  newPos_Callback(api.getPosition());
  function newPos_Callback(newPos)
    % Display the current point position in a text label
    api.setString(sprintf('(%1.0f,%1.0f)',newPos(1),newPos(2)));
  end %newPos_Callback
end %impointBehavior_R2006b
</pre>
<p>The code above, when run in R2006b, produces the desired behavior of displaying a text object containing the point coordinates that moves around with the point as it is dragged around the axes.<br />
In R2009b, <a target="_blank" rel="nofollow" href="http://www.mathworks.com/access/helpdesk/help/toolbox/images/impoint.html"><b><i>impoint</i></b></a> is now a true MATLAB class using the new <a target="_blank" rel="nofollow" href="http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_oop/brqy3km-6.html"><b><i>classdef</i></b></a> syntax, so I wanted to update the existing code. Initially this appeared to be a straightforward translation of the code to make use of the new <b><i>impoint</i></b> class syntax. The first attempt to rewrite the code was:</p>
<pre lang="matlab">
function impointBehavior_R2009b
%IMPOINTBEHAVIOR_R2009B shows the undesirable behavior when
%using the setString method in R2009b.
  % Display the image in a figure window
  figure;  imshow('rice.png');
  h = impoint(gca,100,200);
  % Add a new position callback to set the text string
  h.addNewPositionCallback(@newPos_Callback);
  % Construct boundary constraint function so we can't go outside the axes
  fcn = makeConstrainToRectFcn('impoint',get(gca,'XLim'),get(gca,'YLim'));
  % Enforce boundary constraint function
  h.setPositionConstraintFcn(fcn);
  % Fire callback so we get initial text
  newPos_Callback(h.getPosition());
  function newPos_Callback(newPos)
    % Display the current point position in a text label
    h.setString(sprintf('(%1.0f,%1.0f)',newPos(1),newPos(2)))
  end %newPos_Callback
end %impointBehavior_R2009b
</pre>
<p>Unfortunately, when this code is run, dragging the mouse around the axes produces a trail of labels as shown below:<br />
<center><figure style="width: 295px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Before - buggy behavior" src="https://undocumentedmatlab.com/images/impoint_before.png" title="Before - buggy behavior" width="295" height="295" /><figcaption class="wp-caption-text">Before - buggy behavior</figcaption></figure></center><br />
Opening up <b><i>impoint</i></b>.m in the editor and tracing the code revealed that <b><i>impoint</i></b>&#8216;s <i>setString</i> method creates a new <b><i>text</i></b> object each time it is used. I reported this to MATLAB and the bug is now documented on the MathWorks Support site (<a target="_blank" rel="nofollow" href="http://www.mathworks.com/support/bugreports/574846">574846</a>).</p>
<h3>The solution</h3>
<p>So how do we work around this bug to get to the behavior we want? One solution would be to rewrite the offending MATLAB code but this is somewhat risky in terms of maintainability and compatibility.<br />
A more elegant solution is to subclass the <b><i>impoint</i></b> class and substitute the <i>setString</i> behavior we want. Looking at the <b><i>impoint</i></b> code we find that <b><i>impoint</i></b> is a subclass of <a target="_blank" rel="nofollow" href="http://www.mathworks.com/access/helpdesk/help/toolbox/images/imroi.html"><b><i>imroi</i></b></a>. In the <b><i>imroi</i></b> property declarations we see a number of undocumented properties that are protected. We can access these properties in a subclass but not outside the class. One of these undocumented properties is h_group which is an <b><i>hggroup</i></b> that contains the handle graphic objects that make up the <b><i>impoint</i></b> on the screen. The label, when created, becomes part of this <b><i>hggroup</i></b> with its <b>Tag</b> property set to &#8216;label&#8217;. When performing the <i>setString</i> method the behavior we want to see is that if the <b><i>text</i></b> object exists we want to update its <b>String</b> property. If it does not exist we want it to perform its existing functionality:</p>
<pre lang="matlab">
classdef impointtextupdate < impoint
%IMPOINTTEXTUPDATE subclasses impoint to override the setString
%method of impoint so that it does not create a new text object
%each time it is called.
  methods
    function obj = impointtextupdate(varargin)
      obj = obj@impoint(varargin{:});
    end %impointtextupdate
    function setString(obj,str)
      %override impoint setString
      %check to see if there is already a text label
      label = findobj(obj.h_group,'Type','text','Tag','label');
      if isempty(label)
        %do the default behavior
        setString@impoint(obj,str);
      else
        %update the existing tag
        set(label(1),'String',str);
      end %if
    end %setString
  end %methods
end %impointtextupdate
</pre>
<p>Substituting calls to <b><i>impoint</i></b> with the new <b><i>impointupdatetext</i></b> subclass now produces the desired effect as shown below:<br />
<center><figure style="width: 295px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="After - expected behavior" src="https://undocumentedmatlab.com/images/impoint_after.png" title="After - expected behavior" width="295" height="295" /><figcaption class="wp-caption-text">After - expected behavior</figcaption></figure></center></p>
<h3>Conclusions</h3>
<p>This case illustrates a couple of points:</p>
<ul>
<li>Much of the existing code in the MATLAB toolboxes is being updated to the new object oriented syntax. This presents many opportunities to easily and elegantly modify the default behavior without modifying provided toolbox code In the example above we retain all the desirable behavior of <b><i>impoint</i></b> while overriding the undesirable behavior.</li>
<li>Many of the properties and methods in the provided toolbox objects are hidden or protected and are undocumented. It takes some simple detective work to find these out through examining the code. MATLAB is very generous in providing much of the existing code openly. Open the functions and classes you use in the editor to really find out how they work. Over the years I've learned and adopted a lot of useful MATLAB programming patterns by examining the code in the various toolboxes (there are a few coding horrors as well!).</li>
</ul>
<p>I hope to explore some other under-documented features of the IPT and other toolboxes in future posts.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/solving-a-matlab-bug-by-subclassing">Solving a MATLAB bug by subclassing</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/solving-a-matlab-mcos-bug" rel="bookmark" title="Solving a Matlab MCOS bug">Solving a Matlab MCOS bug </a> <small>Matlab has a bug with handling multi-element class-access constructs. This post explains the problem and solution. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/solving-a-matlab-hang-problem" rel="bookmark" title="Solving a Matlab hang problem">Solving a Matlab hang problem </a> <small>A very common Matlab hang is apparently due to an internal timing problem that can easily be solved. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/solving-an-mput-ftp-hang-problem" rel="bookmark" title="Solving an mput (FTP) hang problem">Solving an mput (FTP) hang problem </a> <small>Matlab may hang when using passive FTP commands such as mput and dir. A simple workaround is available to fix this. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/simple-gui-tabs-for-advanced-matlab-trading-app" rel="bookmark" title="Simple GUI Tabs for Advanced Matlab Trading App">Simple GUI Tabs for Advanced Matlab Trading App </a> <small>A new File Exchange utility enables to easily design GUI tabs using Matlab's GUIDE...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/solving-a-matlab-bug-by-subclassing/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
	</channel>
</rss>
