<?xml version="1.0" encoding="UTF-8"?> <rss
version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
><channel><title>Undocumented Matlab &#187; Callbacks</title> <atom:link href="http://undocumentedmatlab.com/blog/tag/callbacks/feed/" rel="self" type="application/rss+xml" /><link>http://undocumentedmatlab.com</link> <description>Charting Matlab's unsupported hidden underbelly</description> <lastBuildDate>Thu, 02 Feb 2012 00:24:18 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.1.1</generator> <item><title>Matlab-Java memory leaks, performance</title><link>http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/</link> <comments>http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/#comments</comments> <pubDate>Fri, 20 Jan 2012 00:56:10 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Memory]]></category> <category><![CDATA[Semi-documented feature]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[Performance]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2665</guid> <description><![CDATA[Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/performance-scatter-vs-line/' rel='bookmark' title='Performance: scatter vs. line'>Performance: scatter vs. line</a> <small>In many circumstances, the line function can generate visually-identical plots as the scatter function, much faster...</small></li><li><a
href='http://undocumentedmatlab.com/blog/plot-performance/' rel='bookmark' title='Plot performance'>Plot performance</a> <small>Undocumented inner plot mechanisms can be used to significantly improved plotting performance...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/datestr-performance/' rel='bookmark' title='datestr performance'>datestr performance</a> <small>Caching is a simple and very effective means to improve code performance, as demonstrated for the datestr function....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>There are several ways of retrieving information from a Java object into Matlab. On the face of it, all these methods look similar. But it turns out that there are important differences between them in terms of memory leakage and performance.</p><h3 id="Problem">The problem: &#8220;Matlab crashes&#8221; &#8211; now go figure&#8230;</h3><p>A client of one of my Matlab programs recently complained that Matlab crashes after several hours of extensive use of the program. The problem looked like something that is memory related (messages such as Matlab&#8217;s out-of-memory error or Java&#8217;s heap-space error). Apparently this happens even on 64-bit systems having lots of memory, where memory should never be a problem.</p><p>Well, we know that this is only in theory, but in practice Matlab&#8217;s internal memory management has problems that occasionally lead to such crashes. This is one of the reasons, by the way, that recent Matlab releases have added the preference option of increasing the default Java heap space (the previous way to do this was <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/support/solutions/en/data/1-18I2C/">a bit complex</a>). Still, even with a high Java heap space setting and lots of RAM, Matlab crashed after using my program for several hours.</p><p>Not pleasant at all, even a bit of an embarrassment for me. I&#8217;m used to crashing Matlab, but only as a result of my playing around with the internals &#8211; I would hate it to happen to my clients.</p><h3 id="Finding">Finding the leak</h3><p>While we can do little with Matlab&#8217;s internal memory manager, I started searching for the exact location of the memory leak and then to find a way to overcome it. I&#8217;ll save readers the description about the grueling task of finding out exactly where the memory leak occurred in a program that has thousands of lines of code and where events get fired asynchronously on a constant basis. <a
target="_blank" href="http://undocumentedmatlab.com/blog/undocumented-profiler-options/">Matlab Profiler&#8217;s undocumented memory profiling option</a> helped me quite a bit, as well as lots of intuition and trial-and-error. Detecting memory leak is never easy, and I consider myself somewhat lucky this time to have both detected the leak source and a workaround.</p><p>It turned out that the leakage happens in a callback that gets invoked multiple times per second by a Java object (see related articles <a
target="_blank" href="http://undocumentedmatlab.com/blog/uicontrol-callbacks/">here</a> and <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/">here</a>). Each time the Matlab callback function is invoked, it reads the event information from the supplied Java event-data (the callback&#8217;s second input parameter). Apparently, about 1KB of memory gets leaked whenever this event-data is being read. This may appear a very small leak, but multiply this by some 50-100K callback invocations per hour and you get a leakage of 50-100MB/hour. Not a small leak at all; more of a flood you could say&#8230;</p><h3 id="get">Using <i><b>get</b>()</i></h3><p>The leakage culprit turned out to be the following code snippet:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% 160 uSecs per call, with memory leak</span>
eventData  = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>hEventData,<span style="color: #080;">&#123;</span><span style="color:#A020F0;">'EventName'</span>,<span style="color:#A020F0;">'ParamNames'</span>,<span style="color:#A020F0;">'EventData'</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
eventName  = eventData<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span>;
paramNames = eventData<span style="color: #080;">&#123;</span><span style="color: #33f;">2</span><span style="color: #080;">&#125;</span>;
paramData  = eventData<span style="color: #080;">&#123;</span><span style="color: #33f;">3</span><span style="color: #080;">&#125;</span>.<span style="color: #0000FF;">cell</span>;</pre></div></div><p>In this innocent-looking code, <code>hEventData</code> is a Java object that contains the <b>EventName, ParamNames, EventData</b> properties: <b>EventName</b> is a Java <code>String</code>, that is automatically converted by Matlab&#8217;s <i><b>get</b>()</i> function into a Matlab string (<i><b>char</b></i> array); <b>ParamNames</b> is a Java array of <code>String</code>s, that gets automatically converted into a Matlab cell-array of string; and <b>EventData</b> is a Java array of <code>Object</code>s that needs to be converted into a Matlab cell array using the built-in <i><b>cell</b></i> function, as <a
target="_blank" href="http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/">described</a> in one of my recent articles.</p><p>The code is indeed innocent, works really well and is actually extremely fast: each invocation takes of this code segment takes less than 0.2 millisecs. Unfortunately, because of the memory leak I needed to find a better alternative.</p><h3 id="handle">Using <i><b>handle</b>()</i></h3><p>The first idea was to use the built-in <i><b>handle</b>()</i> function, under the assumption that it would solve the memory leak, as <a
target="_blank" rel="nofollow" href="http://mathforum.org/kb/message.jspa?messageID=5950839">reported here</a>. In fact, MathWorks specifically advises to use <i><b>handle</b>()</i> rather than to work with &#8220;naked&#8221; Java objects, when <a
target="_blank" href="http://undocumentedmatlab.com/blog/uicontrol-callbacks/#memory_leak">setting Java object callbacks</a>. The official documentation of the <i><b>set</b></i> function <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/ref/set.html#f67-433534">says</a>:</p><blockquote><p>Do not use the set function on Java objects as it will cause a memory leak.</p></blockquote><p>It stands to reason then that a similar memory leak happens with <i><b>get</b></i> and that a similar use of <i><b>handle</b></i> would solve this problem:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% 300 uSecs per call, with memory leak</span>
s = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span>hEventData<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
eventName  = s.<span style="">EventName</span>;
paramNames = s.<span style="">ParamNames</span>;
paramData  = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>s.<span style="">EventData</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Unfortunately, this variant, although working correctly, still leaks memory, and also performs almost twice as worse than the original version, taking some 0.3 milliseconds to execute per invocation. Looks like this is a dead end.</p><h3 id="accessor">Using Java accessor methods</h3><p>The next attempt was to use the Java object&#8217;s internal accessor methods for the requested properties. These are <code>public</code> methods of the form <i>getXXX(), isXXX(), setXXX()</i> that enable Matlab to treat XXX as a property by its <i><b>get</b></i> and <i><b>set</b></i> functions. In our case, we need to use the getter methods, as follows:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% 380 uSecs per call, no memory leak</span>
eventName  = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>hEventData.<span style="">getEventName</span><span style="color: #080;">&#41;</span>;
paramNames = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>hEventData.<span style="">getParamNames</span><span style="color: #080;">&#41;</span>;
paramData  = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>hEventData.<span style="">getEventData</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Here, the method <i>getEventName()</i> returns a Java <code>String</code>, that we convert into a Matlab string using the <i><b>char</b></i> function. In our previous two variants, the <i><b>get</b></i> function did this conversion for us automatically, but when we use the Java method directly we need to convert the results ourselves. Similarly, when we call <i>getParamNames()</i>, we need to use the <i><b>cell</b></i> function to convert the Java <code>String[]</code> array into a Matlab cell array.</p><p>This version at last doesn&#8217;t leak any memory. Unfortunately, it has an even worse performance: each invocation takes almost 0.4 milliseconds. The difference may seem insignificant. However, recall that this callback gets called dozens of times each second, so the total adds up quickly. It would be nice if there were a faster alternative that does not leak any memory.</p><h3 id="struct">Using <i><b>struct</b>()</i></h3><p>Luckily, I found just such an alternative. At 0.24 millisecs per invocation, it is almost as fast as the leaky best-performance original <i><b>get</b></i> version. Best of all, it leaks no memory, at least none that I could detect.</p><p>The mechanism relies on the little-known fact that public fields of Java objects can be retrieved in Matlab using the built-in <i><b>struct</b></i> function. For example:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; fields = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>java.<span style="">awt</span>.<span style="color: #0000FF;">Rectangle</span><span style="color: #080;">&#41;</span>
fields = 
             x<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
             y<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
         width<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
        height<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
      OUT_LEFT<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>
       OUT_TOP<span style="color: #F0F;">:</span> <span style="color: #33f;">2</span>
     OUT_RIGHT<span style="color: #F0F;">:</span> <span style="color: #33f;">4</span>
    OUT_BOTTOM<span style="color: #F0F;">:</span> <span style="color: #33f;">8</span>
&nbsp;
&gt;&gt; fields = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>java.<span style="">awt</span>.<span style="">Dimension</span><span style="color: #080;">&#41;</span>
fields = 
     width<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
    height<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span></pre></div></div><p>Note that this useful mechanism is not mentioned in <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_external/f4873.html#f46643">the main documentation page for accessing Java object fields</a>, although it is indeed mentioned in <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_external/f6671.html#f61403">another doc-page</a> &#8211; I guess this is a documentation oversight.</p><p>In any case, I converted my Java object to use public (rather than private) fields, so that I could use this <i><b>struct</b></i> mechanism (Matlab can only access public fields). Yes I know that using private fields is a better programming practice and all that (I&#8217;ve programmed OOP for some 15 years&#8230;), but sometimes we need to do ugly things in the interest of performance. The latest version now looks like this:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% 240 uSecs per call, no memory leak</span>
s = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>hEventData<span style="color: #080;">&#41;</span>;
eventName  = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>s.<span style="">eventName</span><span style="color: #080;">&#41;</span>;
paramNames = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>s.<span style="">paramNames</span><span style="color: #080;">&#41;</span>;
paramData  = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>s.<span style="">eventData</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>This solved the memory leakage issue for my client. I felt fortunate that I was not only able to detect Matlab&#8217;s memory leak but also find a working workaround without sacrificing performance or functionality.</p><p>In this particular case, I was lucky to have full control over my Java object, to be able to convert its fields to become public. Unfortunately, we do not always have similar control over the object that we use, because they were coded by a third party.</p><p>By the way, Matlab itself uses this <i><b>struct</b></i> mechanism in its code-base. For example, Matlab timers are implemented using Java objects (<code>com.mathworks.timer.TimerTask</code>). The timer callback in Matlab code converts the Java timer event data into a Matlab struct using the <i><b>struct</b></i> function, in <i>%matlabroot%/toolbox/matlab/iofun/@timer/timercb.m</i>. The users of the timer callbacks then get passed a simple Matlab EventData struct without ever knowing that the original data came from a Java object.</p><p>As an interesting corollary, this same <i><b>struct</b></i> mechanism can be used to detect internal properties of Matlab class objects. For example, in the timers again, we can get the underlying timer&#8217;s Java object as follows (note the highlighted warning, which I find a bit ironic given the context):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; timerObj = timerfind
&nbsp;
   Timer Object<span style="color: #F0F;">:</span> timer-<span style="color: #33f;">1</span>
&nbsp;
   Timer Settings
      ExecutionMode<span style="color: #F0F;">:</span> singleShot
             Period<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>
           BusyMode<span style="color: #F0F;">:</span> drop
            Running<span style="color: #F0F;">:</span> off
&nbsp;
   Callbacks
           TimerFcn<span style="color: #F0F;">:</span> @myTimerFcn
           ErrorFcn<span style="color: #F0F;">:</span> <span style="color:#A020F0;">''</span>
           StartFcn<span style="color: #F0F;">:</span> <span style="color:#A020F0;">''</span>
            StopFcn<span style="color: #F0F;">:</span> <span style="color:#A020F0;">''</span>
&nbsp;
&gt;&gt; timerFields = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>timerObj<span style="color: #080;">&#41;</span>
<span style="display:block;background-color: #ffc;"><span style="color: #0000FF;">Warning</span><span style="color: #F0F;">:</span> Calling <span style="color: #0000FF;">STRUCT</span> on an object prevents the object from hiding its implementation details and should thus be avoided.</span><span style="display:block;background-color: #ffc;"><span style="">Use</span> <span style="color: #0000FF;">DISP</span> or DISPLAY to see the visible public details of an object. <span style="">See</span> <span style="color:#A020F0;">'help struct'</span> <span style="color: #0000FF;">for</span> <span style="color: #0000FF;">more</span> information.</span><span style="display:block;background-color: #ffc;"><span style="color: #080;">&#40;</span><span style="color: #0000FF;">Type</span> &quot;warning off MATLAB<span style="color: #F0F;">:</span>structOnObject&quot; to suppress this <span style="color: #0000FF;">warning</span>.<span style="color: #080;">&#41;</span></span>timerFields = 
         ud<span style="color: #F0F;">:</span> <span style="color: #080;">&#123;</span><span style="color: #080;">&#125;</span>
    jobject<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 javahandle.<span style="">com</span>.<span style="">mathworks</span>.<span style="">timer</span>.<span style="">TimerTask</span><span style="color: #080;">&#93;</span></pre></div></div><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/performance-scatter-vs-line/' rel='bookmark' title='Performance: scatter vs. line'>Performance: scatter vs. line</a> <small>In many circumstances, the line function can generate visually-identical plots as the scatter function, much faster...</small></li><li><a
href='http://undocumentedmatlab.com/blog/plot-performance/' rel='bookmark' title='Plot performance'>Plot performance</a> <small>Undocumented inner plot mechanisms can be used to significantly improved plotting performance...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/datestr-performance/' rel='bookmark' title='datestr performance'>datestr performance</a> <small>Caching is a simple and very effective means to improve code performance, as demonstrated for the datestr function....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/feed/</wfw:commentRss> <slash:comments>9</slash:comments> </item> <item><title>Common javacomponent problems</title><link>http://undocumentedmatlab.com/blog/common-javacomponent-problems/</link> <comments>http://undocumentedmatlab.com/blog/common-javacomponent-problems/#comments</comments> <pubDate>Wed, 07 Dec 2011 18:00:38 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[GUI]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[Semi-documented function]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[GUIDE]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2607</guid> <description><![CDATA[The javacomponent function is very useful for placing Java components on-screen, but has a few quirks.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/javacomponent/' rel='bookmark' title='The javacomponent function'>The javacomponent function</a> <small>Matlab's built-in javacomponent function can be used to display Java components in Matlab application - this article details its usages and limitations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/javacomponent-background-color/' rel='bookmark' title='Javacomponent background color'>Javacomponent background color</a> <small>This article explains how to align Java component background color with a Matlab color....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-and-the-event-dispatch-thread-edt/' rel='bookmark' title='Matlab and the Event Dispatch Thread (EDT)'>Matlab and the Event Dispatch Thread (EDT)</a> <small>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes-2/' rel='bookmark' title='Customizing uitree nodes &#8211; part 2'>Customizing uitree nodes &#8211; part 2</a> <small>This article shows how Matlab GUI tree nodes can be customized with checkboxes and similar controls...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>The <i><b>javacomponent</b></i> function, which I described <a
target="_blank" href="http://UndocumentedMatlab.com/blog/javacomponent/">here</a> last year, is a very important built-in Matlab function that enables placing Java components in Matlab figure GUI. Using <i><b>javacomponent</b></i> is pretty straight-forward. However, there are a few quirks that users should be aware of. In today&#8217;s article I&#8217;ll try to highlight some of them and discuss workarounds.</p><h3 id="figure-vis">Figure visibility</h3><p>Java components can only be placed onscreen when their containing Matlab figure has been made visible. This means that calls to <i><b>javacomponent</b></i> cannot be placed at the GUIDE-created *_OpeningFcn() function, because that function is invoked <i>before</i> the figure window is made visible.</p><p>Of course, we can always force the figure to become visible by setting the figure&#8217;s <b>Visible</b> property to <code>'on'</code> in this function, before calling our <i><b>javacomponent</b></i>s. But IMHO, a better option would be to simply place the <i><b>javacomponent</b></i>s in the corresponding GUIDE-created *_OutputFcn() function, which is invoked <i>after</i> the figure window is made visible.</p><h3 id="parent-vis">Auto-hiding with parent container</h3><p>Java components are not automatically hidden with their ancestor container panel. This is also the root cause of the failure of Java components to disappear when switching tabs in a <i><b>uitab</b></i>.</p><p>One simple workaround for this that I often use is to link the <b>Visible</b> properties of the <i><b>javacomponent</b></i> container and the parent container:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jButton = javax.<span style="">swing</span>.<span style="">JButton</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'click me!'</span><span style="color: #080;">&#41;</span>;
<span style="color: #080;">&#91;</span>jhButton, hContainer<span style="color: #080;">&#93;</span> = javacomponent<span style="color: #080;">&#40;</span>jButton, <span style="color: #080;">&#91;</span><span style="color: #33f;">100</span>,<span style="color: #33f;">100</span>,<span style="color: #33f;">60</span>,<span style="color: #33f;">30</span><span style="color: #080;">&#93;</span>, hParent<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">setappdata</span><span style="color: #080;">&#40;</span>hParent, <span style="color:#A020F0;">'linked_props__'</span>, linkprop<span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span>hParent,hContainer<span style="color: #080;">&#93;</span>,<span style="color:#A020F0;">'Visible'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>This has indeed been fixed in R2010b. If you ask me, this should have been standard behavior of <i><b>javacomponent</b></i> since the very beginning&#8230;</p><p>Although there is no need for the workaround in R2010b onward, I usually keep the workaround because it doesn&#8217;t hurt and enables backward compatibility for users who may have an older Matlab release.</p><h3 id="parent-types">Possible parent container types</h3><p><i><b>javacomponent</b></i> accepts parent handles that are figures, toolbars, <i><b>uipanel</b></i>s, or <a
target="_blank" href="http://UndocumentedMatlab.com/blog/matlab-layout-managers-uicontainer-and-relatives"><i><b>uicontainer</b></i>s</a> (some of these are not documented as possible parents in some Matlab releases, but they are). Since R2008a, parents of type <a
target="_blank" href="http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool/"><i><b>uisplittool</b></i> and <i><b>uitogglesplittool</b></i></a> can also be used. Unfortunately, frames are not <i><b>uicontainer</b></i>s and, therefore, cannot be used as <i><b>javacomponent</b></i> parents.</p><p>Note: Due to a bug in R2007a, <i><b>javacomponent</b></i>s cannot be added to <i><b>uicontainer</b></i>s, since <i>javacomponent.m</i> checks if <code>isa(hParent,'uicontainer')</code> (and similarly for <code>'uiflowcontainer', 'uigridcontainer'</code>), instead of <code>isa(hParent,'hg.uicontainer')</code> (and similarly for the others). If we modify <i>javacomponent.m</i> accordingly (add &#8220;hg.&#8221; in lines 98-100), this bug will be fixed. Since R2007b, <code>isa(…,'hg.uicontainer')</code> is equivalent to <code>isa(…,'uicontainer')</code>, so this fix is unnecessary.</p><h3 id="inputs">Input parameters</h3><p>Unlike many other Matlab functions, <i><b>javacomponent</b></i> does not accept optional parameter-value (P-V) pairs. If we want to customize the appearance of the Java component, it is better to create it , customize it, and only then to present it onscreen using <i><b>javacomponent</b></i>. If we first present the component and then customize it, there might be all sorts of undesirable flicker effects while the component is changing its properties.</p><p>One of the parameters that unfortunately cannot be customized before calling <i><b>javacomponent</b></i> is the component&#8217;s position onscreen. <i><b>javacomponent</b></i> only accepts a position vector in pixel units. To modify the component to use normalized units, we need to modify the container&#8217;s properties:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jButton = javax.<span style="">swing</span>.<span style="">JButton</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'click me!'</span><span style="color: #080;">&#41;</span>;
<span style="color: #080;">&#91;</span>jhButton, hContainer<span style="color: #080;">&#93;</span> = javacomponent<span style="color: #080;">&#40;</span>jButton, <span style="color: #080;">&#91;</span><span style="color: #33f;">100</span>,<span style="color: #33f;">100</span>,<span style="color: #33f;">60</span>,<span style="color: #33f;">30</span><span style="color: #080;">&#93;</span>, <span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hContainer, <span style="color:#A020F0;">'Units'</span>,<span style="color:#A020F0;">'norm'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Similarly, we can set the container&#8217;s <b>UserData</b> and <b>ApplicationData</b> only after the call to <i><b>javacomponent</b></i>.</p><h3 id="bg-color">Background color</h3><p>The default background color of <i><b>javacomponent</b></i>s is a slightly different shade of gray than the default <i><b>uicontrol</b></i> background color. Please refer to my recent <a
target="_blank" href="http://UndocumentedMatlab.com/blog/javacomponent-background-color/">article</a> for a detailed discussion of this issue.</p><h3 id="alignment">Vertical alignment</h3><p>Java components are slightly mis-aligned vertically with combo-box (<b>Style</b>=&#8217;popup&#8217;) <i><b>uicontrol</b></i>s, even when positioned using the same Y position. This is actually due to an apparent bug in Matlab&#8217;s implementation of the combo-box <i><b>uicontrol</b></i>, and not in the Java component&#8217;s: Apparently, the Matlab control does not obey its specified height and uses some other default height.</p><p>If we place <i><b>javacomponent</b></i>s side-by-side with a regular Matlab popup <i><b>uicontrol</b></i>s and give them all the same Y position, we can see this mis-alignment. It is only a few pixels, but the effect is visible and disturbing. To fix it, we need to add a small offset to the <i><b>javacomponent</b></i>&#8216;s container&#8217;s <b>Position</b> property to make both the initial Y position slightly lower, and the height value slightly higher than the values for the corresponding Matlab combo-box control.</p><h3 id="callbacks">Callbacks</h3><p>Unlike Matlab <i><b>uicontrol</b></i> callbacks, Java callbacks are activated even when the affected value does not change. Therefore, setting a value in the component&#8217;s callback could well cause an infinite loop of invoked callbacks.</p><p>Matlab programmers often use the practice of modifying component value within the callback function, as a means of fixing user-entered values to be within a certain data range, or in order to format the displayed value. This is relatively harmless in Matlab (if done correctly) since updating a Matlab <i><b>uicontrol</b></i>&#8216;s value to the current value does not retrigger the callback. But since this is not the case with Java callbacks, users should beware not to use the same practice there. In cases where this cannot be avoided, users should at least implement some sort of <a
target="_blank" href="http://undocumentedmatlab.com/blog/controlling-callback-re-entrancy/">callback re-entrancy prevention logic</a>.</p><h3 id="EDT">EDT</h3><p>Java components typically need to use the independent Java Event processing Thread (EDT). EDT is very important for Matlab GUI, as explained in <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-and-the-event-dispatch-thread-edt/">this article</a>. Failure to use EDT properly in Matlab can lead to unexpected GUI behavior and even Matlab hangs or crashes.</p><p>If the <i><b>javacomponent</b></i> function is called in a very specific syntax format where the first input arg is a string (the name of the Java class to be created), then the newly-created component is placed on the EDT. However, this is not the normal manner in which <i><b>javacomponent</b></i> is used: A much more typical use-case is where <i><b>javacomponent</b></i> is passed a reference handle to a previously-created Java component. In such cases, it is the user&#8217;s responsibility to place the component on the EDT. Until R2008a this should be done using the <i><b>awtcreate</b></i> function; since R2008b, we can use the much simpler <i><b>javaObjectEDT</b></i> function (<i><b>javaObjectEDT</b></i> actually existed since R2008a, but was buggy on that release so I suggest using it only starting in R2008b; it became documented starting in R2009a). In fact, modern <i><b>javacomponent</b></i> saves us the trouble, by automatically using <i><b>javaObjectEDT</b></i> to auto-delegate the component onto the EDT, even if we happen to have created it on the MT.</p><p>The paragraph above may lead us to believe that we only need to worry about EDT in R2008a and earlier. Unfortunately, this is not the case. Modern GUI requires using many sub-components, that are attached to their main component (e.g., CellRenderers and CellEditors). <i><b>javacomponent</b></i> only bothers to place the main component on the EDT &#8211; not any of the sub-components. We need to handle these separately. Liberally auto-delegating components to the EDT seems like a safe and painless habit to have.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/javacomponent/' rel='bookmark' title='The javacomponent function'>The javacomponent function</a> <small>Matlab's built-in javacomponent function can be used to display Java components in Matlab application - this article details its usages and limitations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/javacomponent-background-color/' rel='bookmark' title='Javacomponent background color'>Javacomponent background color</a> <small>This article explains how to align Java component background color with a Matlab color....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-and-the-event-dispatch-thread-edt/' rel='bookmark' title='Matlab and the Event Dispatch Thread (EDT)'>Matlab and the Event Dispatch Thread (EDT)</a> <small>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes-2/' rel='bookmark' title='Customizing uitree nodes &#8211; part 2'>Customizing uitree nodes &#8211; part 2</a> <small>This article shows how Matlab GUI tree nodes can be customized with checkboxes and similar controls...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/common-javacomponent-problems/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Controlling callback re-entrancy</title><link>http://undocumentedmatlab.com/blog/controlling-callback-re-entrancy/</link> <comments>http://undocumentedmatlab.com/blog/controlling-callback-re-entrancy/#comments</comments> <pubDate>Wed, 10 Aug 2011 18:00:57 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Guest bloggers]]></category> <category><![CDATA[GUI]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[COM]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Malcolm Lidierth]]></category> <category><![CDATA[Pure Matlab]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2403</guid> <description><![CDATA[Callback reentrancy is a major problem for frequently-fired events. Luckily, it can easily be solved.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/continuous-slider-callback/' rel='bookmark' title='Continuous slider callback'>Continuous slider callback</a> <small>Matlab slider uicontrols do not enable a continuous-motion callback by default. This article explains how this can be achieved using undocumented features....</small></li><li><a
href='http://undocumentedmatlab.com/blog/controlling-plot-data-tips/' rel='bookmark' title='Controlling plot data-tips'>Controlling plot data-tips</a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/uicontrol-callbacks/' rel='bookmark' title='Uicontrol callbacks'>Uicontrol callbacks</a> <small>This post details undocumented callbacks exposed by the underlying Java object of Matlab uicontrols, that can be used to modify the control's behavior in a multitude of different events...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><i>I&#8217;d like to welcome guest blogger <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/23816">Malcolm Lidierth</a> of King&#8217;s College London. Malcolm is well known in the Matlab-Java community for his <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/15580-using-java-swing-components-in-matlab">jcontrol utility</a>. Some months ago, I mentioned his work on another File Exchange contribution, <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/28326-mutilities">MUtilities</a> when I discussed <a
target="_blank" href="http://undocumentedmatlab.com/blog/transparent-matlab-figure-window/">transparent Matlab figure windows</a>. Today, Malcolm discusses one of his lesser-known but extremely important <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26027-ismultiplecall">isMultipleCall utility</a>.</i></p><p>Every now and again, a very simple bit of code turns out to be more useful than the author initially imagined. Something I have repeatedly used is the <i><b>isMultipleCall</b></i> function which I <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26027-ismultiplecall">posted</a> to MATLAB Central&#8217;s File Exchange a year or so ago.</p><p>The <i><b>isMultipleCall</b></i> function uses fully-documented pure-MATLAB to extend the control that can be achieved over callbacks.</p><p>Here was the problem: I had a modular system built in MATLAB which allowed third-party developers to add their own plugins. I wanted a mechanism to force the dismissal (&#8220;bail-out&#8221;) of a callback even when the <b>Interruptible</b> property of the parent object was set to &#8216;on&#8217;. Such callback re-entrancy issues are common for rapidly-firing events, and debugging and fixing them is usually <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/answers/5809-how-to-implement-a-speed-limit-for-gui-button-press">not easy</a>.</p><p>The callback&#8217;s dismissal code would need to be fast because it might be called many dozens of times, e.g. in a <b>WindowButtonMotion</b> callback. An obvious approach was to check the function call stack using MATLAB&#8217;s <i><b>dbstack</b></i> function. Although, at first, this seemed likely to be too slow, profiling showed it was not – taking &lt; 40&micro;sec per call &#8211; and within a <b>WindowButtonMotion</b> callback in a real GUI, I could not perceive any slowing of the code.</p><p>Here is the function:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> <span style="color: #0000FF;">flag</span>=isMultipleCall<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
  <span style="color: #0000FF;">flag</span> = <span style="color: #0000FF;">false</span>; 
  <span style="color: #228B22;">% Get the stack</span>
  s = <span style="color: #0000FF;">dbstack</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
  <span style="color: #0000FF;">if</span> numel<span style="color: #080;">&#40;</span>s<span style="color: #080;">&#41;</span>&lt; =<span style="color: #33f;">2</span>
    <span style="color: #228B22;">% Stack too short for a multiple call</span>
    <span style="color: #0000FF;">return</span>
  <span style="color: #0000FF;">end</span>
&nbsp;
  <span style="color: #228B22;">% How many calls to the calling function are in the stack?</span>
  names = <span style="color: #080;">&#123;</span>s<span style="color: #080;">&#40;</span><span style="color: #F0F;">:</span><span style="color: #080;">&#41;</span>.<span style="">name</span><span style="color: #080;">&#125;</span>;
  TF = <span style="color: #0000FF;">strcmp</span><span style="color: #080;">&#40;</span>s<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>.<span style="">name</span>,names<span style="color: #080;">&#41;</span>;
  count = <span style="color: #0000FF;">sum</span><span style="color: #080;">&#40;</span>TF<span style="color: #080;">&#41;</span>;
  <span style="color: #0000FF;">if</span> count&gt;<span style="color: #33f;">1</span>
    <span style="color: #228B22;">% More than 1</span>
    <span style="color: #0000FF;">flag</span> = <span style="color: #0000FF;">true</span>; 
  <span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">end</span></pre></div></div><p>With <i><b>isMultipleCall</b></i> invoked from another function (see note below), <i><b>dbstack</b></i> will return a structure with a minimum of 2 elements – the first relating to <i><b>isMultipleCall</b></i> itself and the second to the calling function. So with <i><b>numel</b></i>(s) &lt;= 2, there can be no multiple calls and we can return false immediately thus saving time in doing any further testing.  For <i><b>numel</b></i>(s) &gt; 2 we simply check to see whether the calling functions referenced in s(2) appears anywhere else on the stack. If it does, then we return true; otherwise false.</p><p>Then, in our callback code we simply use:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">if</span> isMultipleCall<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;  <span style="color: #0000FF;">return</span>;  <span style="color: #0000FF;">end</span></pre></div></div><p>If this line is placed first in the callback function code, it essentially mimics the behavior that you might expect after setting the <b>Interruptible</b> property of the event firing object to &#8216;off&#8217;. Adding a <i><b>drawnow()</b></i> at the end of the callback will ensure that any waiting callbacks in the queue are dismissed:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> MyCallback<span style="color: #080;">&#40;</span>hObj, EventData<span style="color: #080;">&#41;</span>
  <span style="color: #228B22;">% Quick bail-out if callback code is called before another has ended</span>
  <span style="color: #0000FF;">if</span> isMultipleCall<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;  <span style="color: #0000FF;">return</span>;  <span style="color: #0000FF;">end</span>
&nbsp;
  <span style="color: #F0F;">...</span>  <span style="color: #228B22;">% do some actual callback work here</span>
  <span style="color: #0000FF;">drawnow</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>There are several ways in which <i><b>isMultipleCall</b></i> can extend the standard MALAB functionality. First, by moving <i><b>isMultipleCall</b></i> reference from the first line of the callback we can create both an interruptible and an uninteruptible code block, e.g.</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> MyCallback<span style="color: #080;">&#40;</span>hObj, EventData<span style="color: #080;">&#41;</span>
&nbsp;
  <span style="color: #228B22;">%Code Block 1</span>
  <span style="color: #F0F;">...</span>
&nbsp;
  <span style="color: #0000FF;">if</span> isMultipleCall<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;  <span style="color: #0000FF;">return</span>;  <span style="color: #0000FF;">end</span>
&nbsp;
  <span style="color: #228B22;">%Code Block 2</span>
  <span style="color: #F0F;">...</span>
&nbsp;
  <span style="color: #0000FF;">drawnow</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>Second, as <i><b>isMultipleCall</b></i> controls the callbacks  &#8211; not the objects that trigger them &#8211; we can individually control the callbacks of objects which fire multiple events. That is particularly useful with Java components, which gives a third extension – <i><b>isMultipleCall</b></i> can be used in any function: not just the callbacks of standard MATLAB components, but also of Java or COM components.<br
/>  <br
/> Finally, as the callback, not the object is being controlled, we can control a callback that may be shared between multiple objects e.g. a menu component and a toolbar button.</p><p>Not bad for 13 lines of code.</p><p>Note: <i><b>isMultipleCall</b></i> must be called from a function, not from a string in the callback property.</p><p>Do you have any other favorite mechanism for controlling callback re-entrancy? If so, please <a
href="http://UndocumentedMatlab.com/blog/controlling-callback-re-entrancy/#respond">post a comment</a>.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/continuous-slider-callback/' rel='bookmark' title='Continuous slider callback'>Continuous slider callback</a> <small>Matlab slider uicontrols do not enable a continuous-motion callback by default. This article explains how this can be achieved using undocumented features....</small></li><li><a
href='http://undocumentedmatlab.com/blog/controlling-plot-data-tips/' rel='bookmark' title='Controlling plot data-tips'>Controlling plot data-tips</a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/uicontrol-callbacks/' rel='bookmark' title='Uicontrol callbacks'>Uicontrol callbacks</a> <small>This post details undocumented callbacks exposed by the underlying Java object of Matlab uicontrols, that can be used to modify the control's behavior in a multitude of different events...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/controlling-callback-re-entrancy/feed/</wfw:commentRss> <slash:comments>11</slash:comments> </item> <item><title>uisplittool &amp; uitogglesplittool callbacks</title><link>http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool-callbacks/</link> <comments>http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool-callbacks/#comments</comments> <pubDate>Wed, 15 Dec 2010 18:00:35 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Figure window]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[Hidden property]]></category> <category><![CDATA[Toolbar]]></category> <category><![CDATA[uitools]]></category> <category><![CDATA[uiundo]]></category> <category><![CDATA[Undocumented function]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=1999</guid> <description><![CDATA[Matlab's undocumented uisplittool and uitogglesplittool are powerful toolbar controls - this article explains how to customize their behavior<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool/' rel='bookmark' title='uisplittool &amp; uitogglesplittool'>uisplittool &#038; uitogglesplittool</a> <small>Matlab's undocumented uisplittool and uitogglesplittool are powerful controls that can easily be added to Matlab toolbars - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/uicontrol-callbacks/' rel='bookmark' title='Uicontrol callbacks'>Uicontrol callbacks</a> <small>This post details undocumented callbacks exposed by the underlying Java object of Matlab uicontrols, that can be used to modify the control's behavior in a multitude of different events...</small></li><li><a
href='http://undocumentedmatlab.com/blog/figure-toolbar-components/' rel='bookmark' title='Figure toolbar components'>Figure toolbar components</a> <small>Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to access existing toolbar icons and how to add non-button toolbar components....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>Last week, I presented the undocumented <i><b>uisplittool</b></i> and <i><b>uitogglesplittool</b></i> functions and showed how they can be added to a Matlab figure toolbar. Today I wish to conclude this topic by explaining how these controls can be customized with user-defined callbacks and pop-up menus.</p><h3 id="Callbacks">Callback functionality</h3><p>Both <i><b>uisplittool</b></i> and <i><b>uitogglesplittool</b></i> have a <strong>Callback</strong> property, in addition to the standard <strong>ClickedCallback</strong> property that is available in <i><b>uipushtool</b></i>s and <i><b>uitoggletool</b></i>s.</p><p>The standard <strong>ClickedCallback</strong> is invoked when the main button is clicked, while <strong>Callback</strong> is invoked when the narrow arrow button is clicked. <i><b>uitogglesplittool</b></i>, like <i><b>uitoggletool</b></i>, also has settable <strong>OnCallback</strong> and <strong>OffCallback</strong> callback properties.</p><p>The accepted convention is that <strong>ClickedCallback</strong> should invoke the default control action (in our case, an Undo/Redo of the topmost <a
target="_blank" href="http://undocumentedmatlab.com/blog/uiundo-matlab-undocumented-undo-redo-manager/">uiundo action stack</a>), while <strong>Callback</strong> should display a drop-down of selectable actions.</p><p>While this can be done programmatically using the <strong>Callback</strong> property, this functionality is already pre-built into <i><b>uisplittool</b></i> and <i><b>uitogglesplittool</b></i> for our benefit. To access it, we need to get the control&#8217;s underlying Java component.</p><p>Accessing the underlying Java component is normally done using the <a
target="_blank" href="http://undocumentedmatlab.com/blog/findjobj-find-underlying-java-object/">findjobj utility</a>, but in this case we have a shortcut: the control handle&#8217;s hidden <strong>JavaContainer</strong> property that holds the underlying <i>com.mathworks.hg.peer.SplitButtonPeer</i> (or <i>.ToggleSplitButtonPeer</i>) Java reference handle. This Java object&#8217;s <strong>MenuComponent</strong> property returns a reference to the control&#8217;s drop-down sub-component (which is a <i>com.mathworks.mwswing.MJPopupMenu</i> object):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; jUndo = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>hUndo,<span style="color:#A020F0;">'JavaContainer'</span><span style="color: #080;">&#41;</span>
jUndo =
com.<span style="">mathworks</span>.<span style="">hg</span>.<span style="">peer</span>.<span style="">SplitButtonPeer</span>@f09ad5
&nbsp;
&gt;&gt; jMenu = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>jUndo,<span style="color:#A020F0;">'MenuComponent'</span><span style="color: #080;">&#41;</span>  <span style="color: #228B22;">% or: =jUndo.getMenuComponent</span>
jMenu =
com.<span style="">mathworks</span>.<span style="">mwswing</span>.<span style="">MJPopupMenu</span><span style="color: #080;">&#91;</span>Dropdown Picker ButtonMenu,<span style="color: #F0F;">...</span><span style="color: #080;">&#93;</span></pre></div></div><p>Let&#8217;s add a few simple textual options:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jOption1 = jMenu.<span style="">add</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Option #1'</span><span style="color: #080;">&#41;</span>;
jOption1 = jMenu.<span style="">add</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Option #2'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>jOption1, <span style="color:#A020F0;">'ActionPerformedCallback'</span>, <span style="color:#A020F0;">'disp('</span><span style="color:#A020F0;">'option #1'</span><span style="color:#A020F0;">')'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>jOption2, <span style="color:#A020F0;">'ActionPerformedCallback'</span>, <span style="color: #080;">&#123;</span>@myCallbackFcn, extraData<span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 320px"><img
alt="setting uisplittool &amp; uitogglesplittool popup-menus" src="http://UndocumentedMatlab.com/images/uisplittool3.png" title="setting uisplittool &amp; uitogglesplittool popup-menus" width="99" height="72" /><p
class="wp-caption-text">setting <i><b>uisplittool</b></i> &amp; <i><b>uitogglesplittool</b></i> popup-menus</p></div></center></p><p>Popup-menus are described in more detail elsewhere (and in future articles). In the past I have already explained how icons and HTML markup can be added to menu items. Sub-menus can also be added.</p><h3 id="Example">A complete example</h3><p>Let&#8217;s now use this information, together with last year&#8217;s <a
target="_blank" href="http://undocumentedmatlab.com/blog/tag/uiundo/">set of articles</a> about Matlab&#8217;s undocumented <i><b>uiundo</b></i> functionality, to generate a complete and more realistic example, of undo/redo toolbar buttons.</p><p>Undo and redo are actions that are particularly suited for <i><b>uisplittool</b></i>, since its main button enables us to easily undo/redo the latest action (like a simple toolbar button, by clicking the main <i><b>uisplittool</b></i> button) as well as select items from the actions drop-down (like a combo-box, by clicking the attached arrow button) – all this using a single component.</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Display our GUI</span>
hEditbox = <span style="color: #0000FF;">uicontrol</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'style'</span>,<span style="color:#A020F0;">'edit'</span>, <span style="color:#A020F0;">'position'</span>,<span style="color: #080;">&#91;</span><span style="color: #33f;">20</span>,<span style="color: #33f;">60</span>,<span style="color: #33f;">40</span>,<span style="color: #33f;">40</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>; 
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hEditbox, <span style="color:#A020F0;">'Enable'</span>,<span style="color:#A020F0;">'off'</span>, <span style="color:#A020F0;">'string'</span>,<span style="color:#A020F0;">'0'</span><span style="color: #080;">&#41;</span>;
hSlider = <span style="color: #0000FF;">uicontrol</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'style'</span>,<span style="color:#A020F0;">'slider'</span>,<span style="color:#A020F0;">'userdata'</span>,hEditbox<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hSlider,<span style="color:#A020F0;">'Callback'</span>,@test_uiundo<span style="color: #080;">&#41;</span>;  
&nbsp;
<span style="color: #228B22;">% Display the figure toolbar that was hidden by the uicontrol function</span>
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span>,<span style="color:#A020F0;">'Toolbar'</span>,<span style="color:#A020F0;">'figure'</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Add the Undo/Redo buttons</span>
hToolbar = findall<span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span>,<span style="color:#A020F0;">'tag'</span>,<span style="color:#A020F0;">'FigureToolBar'</span><span style="color: #080;">&#41;</span>;
hUndo = uisplittool<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'parent'</span>,hToolbar<span style="color: #080;">&#41;</span>;
hRedo = uitogglesplittool<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'parent'</span>,hToolbar<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Load the Redo icon</span>
icon = <span style="color: #0000FF;">fullfile</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">matlabroot</span>,<span style="color:#A020F0;">'/toolbox/matlab/icons/greenarrowicon.gif'</span><span style="color: #080;">&#41;</span>;
<span style="color: #080;">&#91;</span>cdata,map<span style="color: #080;">&#93;</span> = <span style="color: #0000FF;">imread</span><span style="color: #080;">&#40;</span>icon<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Convert white pixels into a transparent background</span>
map<span style="color: #080;">&#40;</span><span style="color: #0000FF;">find</span><span style="color: #080;">&#40;</span>map<span style="color: #080;">&#40;</span><span style="color: #F0F;">:</span>,<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>+map<span style="color: #080;">&#40;</span><span style="color: #F0F;">:</span>,<span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>+map<span style="color: #080;">&#40;</span><span style="color: #F0F;">:</span>,<span style="color: #33f;">3</span><span style="color: #080;">&#41;</span>==<span style="color: #33f;">3</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> = <span style="color: #0000FF;">NaN</span>;
&nbsp;
<span style="color: #228B22;">% Convert into 3D RGB-space</span>
cdataRedo = ind2rgb<span style="color: #080;">&#40;</span>cdata,map<span style="color: #080;">&#41;</span>;
cdataUndo = cdataRedo<span style="color: #080;">&#40;</span><span style="color: #F0F;">:</span>,<span style="color: #080;">&#91;</span><span style="color: #33f;">16</span><span style="color: #F0F;">:</span>-<span style="color: #33f;">1</span><span style="color: #F0F;">:</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>,<span style="color: #F0F;">:</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Add the icon (and its mirror image = undo) to latest toolbar</span>
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hUndo, <span style="color:#A020F0;">'cdata'</span>,cdataUndo, <span style="color:#A020F0;">'tooltip'</span>,<span style="color:#A020F0;">'undo'</span>,<span style="color:#A020F0;">'Separator'</span>,<span style="color:#A020F0;">'on'</span>, <span style="color: #F0F;">...</span>
           <span style="color:#A020F0;">'ClickedCallback'</span>,<span style="color:#A020F0;">'uiundo(gcbf,'</span><span style="color:#A020F0;">'execUndo'</span><span style="color:#A020F0;">')'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hRedo, <span style="color:#A020F0;">'cdata'</span>,cdataRedo, <span style="color:#A020F0;">'tooltip'</span>,<span style="color:#A020F0;">'redo'</span>, <span style="color: #F0F;">...</span>
           <span style="color:#A020F0;">'ClickedCallback'</span>,<span style="color:#A020F0;">'uiundo(gcbf,'</span><span style="color:#A020F0;">'execRedo'</span><span style="color:#A020F0;">')'</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Re-arrange the Undo/Redo buttons  </span>
jToolbar = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>hToolbar,<span style="color:#A020F0;">'JavaContainer'</span><span style="color: #080;">&#41;</span>,<span style="color:#A020F0;">'ComponentPeer'</span><span style="color: #080;">&#41;</span>;
jButtons = jToolbar.<span style="">getComponents</span>;
<span style="color: #0000FF;">for</span> buttonIdx = <span style="color: #0000FF;">length</span><span style="color: #080;">&#40;</span>jButtons<span style="color: #080;">&#41;</span>-<span style="color: #33f;">3</span> <span style="color: #F0F;">:</span> -<span style="color: #33f;">1</span> <span style="color: #F0F;">:</span> <span style="color: #33f;">7</span>  <span style="color: #228B22;">% end-to-front</span>
   jToolbar.<span style="">setComponentZOrder</span><span style="color: #080;">&#40;</span>jButtons<span style="color: #080;">&#40;</span>buttonIdx<span style="color: #080;">&#41;</span>, buttonIdx+<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span>
jToolbar.<span style="">setComponentZOrder</span><span style="color: #080;">&#40;</span>jButtons<span style="color: #080;">&#40;</span>end-<span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>, <span style="color: #33f;">5</span><span style="color: #080;">&#41;</span>;    <span style="color: #228B22;">% Separator</span>
jToolbar.<span style="">setComponentZOrder</span><span style="color: #080;">&#40;</span>jButtons<span style="color: #080;">&#40;</span>end-<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>, <span style="color: #33f;">6</span><span style="color: #080;">&#41;</span>;    <span style="color: #228B22;">% Undo</span>
jToolbar.<span style="">setComponentZOrder</span><span style="color: #080;">&#40;</span>jButtons<span style="color: #080;">&#40;</span><span style="color: #0000FF;">end</span><span style="color: #080;">&#41;</span>, <span style="color: #33f;">7</span><span style="color: #080;">&#41;</span>;      <span style="color: #228B22;">% Redo</span>
jToolbar.<span style="">revalidate</span>;
&nbsp;
<span style="color: #228B22;">% Retrieve redo/undo object</span>
undoObj = <span style="color: #0000FF;">getappdata</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span>,<span style="color:#A020F0;">'uitools_FigureToolManager'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">if</span> <span style="color: #0000FF;">isempty</span><span style="color: #080;">&#40;</span>undoObj<span style="color: #080;">&#41;</span>
   undoObj = uitools.<span style="">FigureToolManager</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span>;
   <span style="color: #0000FF;">setappdata</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span>,<span style="color:#A020F0;">'uitools_FigureToolManager'</span>,undoObj<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span>
&nbsp;
<span style="color: #228B22;">% Populate Undo actions drop-down list</span>
jUndo = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>hUndo,<span style="color:#A020F0;">'JavaContainer'</span><span style="color: #080;">&#41;</span>;
jMenu = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>jUndo,<span style="color:#A020F0;">'MenuComponent'</span><span style="color: #080;">&#41;</span>;
undoActions = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>undoObj.<span style="">CommandManager</span>.<span style="">UndoStack</span>,<span style="color:#A020F0;">'Name'</span><span style="color: #080;">&#41;</span>;
jMenu.<span style="">removeAll</span>;
<span style="color: #0000FF;">for</span> actionIdx = <span style="color: #0000FF;">length</span><span style="color: #080;">&#40;</span>undoActions<span style="color: #080;">&#41;</span> <span style="color: #F0F;">:</span> -<span style="color: #33f;">1</span> <span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>    <span style="color: #228B22;">% end-to-front</span>
    jActionItem = jMenu.<span style="">add</span><span style="color: #080;">&#40;</span>undoActions<span style="color: #080;">&#40;</span>actionIdx<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>jActionItem, <span style="color:#A020F0;">'ActionPerformedCallback'</span>, @myUndoCallbackFcn<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span>
jToolbar.<span style="">revalidate</span>;
&nbsp;
<span style="color: #228B22;">% Drop-down callback function</span>
<span style="color: #0000FF;">function</span> myUndoCallbackFcn<span style="color: #080;">&#40;</span>jActionItem,hEvent<span style="color: #080;">&#41;</span>
    <span style="color: #228B22;">% user processing needs to be placed here</span>
<span style="color: #0000FF;">end</span>  <span style="color: #228B22;">% myUndoCallbackFcn</span></pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 405px"><img
alt="undo/redo buttons implemented using uisplittool" src="http://UndocumentedMatlab.com/images/uisplittool4b.png" title="undo/redo buttons implemented using uisplittool" width="395" height="257" /><p
class="wp-caption-text">undo/redo buttons implemented using <i><b>uisplittool</b></i></p></div></center></p><p>In a real-world application, the code-segment above that populated the drop-down list would be placed within the slider&#8217;s <em>test_uiundo()</em> callback function, and we would set a similar drop-down for the hRedu button. In addition, we would dynamically modify the button tooltips. As a final customization, we could modify the figure&#8217;s main menu. Menu customization will be discussed in a future separate set of articles.</p><p>Have you used <i><b>uisplittool</b></i> or <i><b>uitogglesplittool</b></i> in your GUI? If so, please tell us what use you have made of them, in a comment <a
href="http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool-callbacks/#respond">below</a>.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool/' rel='bookmark' title='uisplittool &amp; uitogglesplittool'>uisplittool &#038; uitogglesplittool</a> <small>Matlab's undocumented uisplittool and uitogglesplittool are powerful controls that can easily be added to Matlab toolbars - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/uicontrol-callbacks/' rel='bookmark' title='Uicontrol callbacks'>Uicontrol callbacks</a> <small>This post details undocumented callbacks exposed by the underlying Java object of Matlab uicontrols, that can be used to modify the control's behavior in a multitude of different events...</small></li><li><a
href='http://undocumentedmatlab.com/blog/figure-toolbar-components/' rel='bookmark' title='Figure toolbar components'>Figure toolbar components</a> <small>Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to access existing toolbar icons and how to add non-button toolbar components....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool-callbacks/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Matlab callbacks for Java events</title><link>http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/</link> <comments>http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/#comments</comments> <pubDate>Tue, 30 Nov 2010 22:09:35 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[High risk of breaking in future versions]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Listeners]]></category> <category><![CDATA[Semi-documented function]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Undocumented function]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[Listener]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=1987</guid> <description><![CDATA[Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/udd-events-and-listeners/' rel='bookmark' title='UDD Events and Listeners'>UDD Events and Listeners</a> <small>UDD event listeners can be used to listen to property value changes and other important events of Matlab objects...</small></li><li><a
href='http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool-callbacks/' rel='bookmark' title='uisplittool &amp; uitogglesplittool callbacks'>uisplittool &#038; uitogglesplittool callbacks</a> <small>Matlab's undocumented uisplittool and uitogglesplittool are powerful toolbar controls - this article explains how to customize their behavior...</small></li><li><a
href='http://undocumentedmatlab.com/blog/udd-and-java/' rel='bookmark' title='UDD and Java'>UDD and Java</a> <small>UDD provides built-in convenience methods to facilitate the integration of Matlab UDD objects with Java code - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/uicontrol-callbacks/' rel='bookmark' title='Uicontrol callbacks'>Uicontrol callbacks</a> <small>This post details undocumented callbacks exposed by the underlying Java object of Matlab uicontrols, that can be used to modify the control's behavior in a multitude of different events...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>A few days ago, a user <a
target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/4291769/how-do-i-notify-a-matlab-object-of-an-event-in-a-java-object">posted a question</a> on StackOverflow asking whether it is possible to trap a Java-based event in a Matlab callback.</p><p>It so happens that only a few weeks ago I completed a consulting project which required exactly this. The project was to integrate a Matlab computational engine with a Java interface to <a
target="_blank" rel="nofollow" href="http://www.interactivebrokers.com/">Interactive Brokers</a> (IB) &#8211; a well-known online brokerage firm. The idea was to use the Java interface to fetch real-time data about securities (stocks, bonds, options etc.), use a Matlab processing utility, then use the Java interface again to send Buy or Sell orders back to IB.</p><p>If you are interested in the final result (i.e., a complete and field-tested Matlab-IB interface), <a
target="_blank" href="http://undocumentedmatlab.com/ib-matlab/">look here</a>.</p><h3 id="challenge">The challenge</h3><p>A big challenge in this project (aside from handling quite a few IB interface quirks), was to propagate events from the Java interface to the Matlab application. This had to be done asynchronously, since events such as order execution can occur at any time following the order placement. Moreover, even simple requests such as retrieving security information (bid/ask prices for example) is handled by IB via Java events, not as simple function return values.</p><p>Handling Java-based events in Matlab is not a trivial task. Not only merely undocumented, but it is also not intuitive. I have spent quite a few hours trying to crack this issue. In fact, I believe it was one of my more challenging tasks in figuring out the undocumented aspects of the Matlab-Java interface. Few other challenges were as difficult, yet with a happy ending (Drag &#038; Drop is a similar issue &#8211; I will describe it in another article sometime).</p><h3 id="solution">The solution</h3><p>Fast-forward all the fruitless attempted variations, here is the bottom line. Refer to the following simple Java class example:</p><div
class="wp_syntax"><div
class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> EventTest
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> java.<span style="color: #006633;">util</span>.<span style="color: #003399;">Vector</span> data <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> java.<span style="color: #006633;">util</span>.<span style="color: #003399;">Vector</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #000066; font-weight: bold;">void</span> addMyTestListener<span style="color: #009900;">&#40;</span>MyTestListener lis<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        data.<span style="color: #006633;">addElement</span><span style="color: #009900;">&#40;</span>lis<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #000066; font-weight: bold;">void</span> removeMyTestListener<span style="color: #009900;">&#40;</span>MyTestListener lis<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        data.<span style="color: #006633;">removeElement</span><span style="color: #009900;">&#40;</span>lis<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> MyTestListener <span style="color: #000000; font-weight: bold;">extends</span> java.<span style="color: #006633;">util</span>.<span style="color: #003399;">EventListener</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">void</span> testEvent<span style="color: #009900;">&#40;</span>MyTestEvent event<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MyTestEvent <span style="color: #000000; font-weight: bold;">extends</span> java.<span style="color: #006633;">util</span>.<span style="color: #003399;">EventObject</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">long</span> serialVersionUID <span style="color: #339933;">=</span> 1L<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">float</span> oldValue,newValue<span style="color: #339933;">;</span>        
        MyTestEvent<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> obj, <span style="color: #000066; font-weight: bold;">float</span> oldValue, <span style="color: #000066; font-weight: bold;">float</span> newValue<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span>obj<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">oldValue</span> <span style="color: #339933;">=</span> oldValue<span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">newValue</span> <span style="color: #339933;">=</span> newValue<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> notifyMyTest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        java.<span style="color: #006633;">util</span>.<span style="color: #003399;">Vector</span> dataCopy<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">synchronized</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            dataCopy <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>java.<span style="color: #006633;">util</span>.<span style="color: #003399;">Vector</span><span style="color: #009900;">&#41;</span>data.<span style="color: #006633;">clone</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i<span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span>dataCopy.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            MyTestEvent event <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyTestEvent<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>MyTestListener<span style="color: #009900;">&#41;</span>dataCopy.<span style="color: #006633;">elementAt</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">testEvent</span><span style="color: #009900;">&#40;</span>event<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div><p>When compiling EventTest.java, three class files are created: EventTest.class, EventTest$MyTestEvent.class and EventTest$MyTestListener.class. Place them on Matlab&#8217;s Java static classpath, using <i><b>edit</b>(&#8216;classpath.txt&#8217;)</i> (using the dynamic classpath causes many problems that using the static classpath solves). They can now be accessed as follows:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">which</span> EventTest
EventTest <span style="color: #0000FF;">is</span> a Java method  <span style="color: #228B22;">% EventTest constructor</span>
&nbsp;
&gt;&gt; evt = EventTest
evt =
EventTest@16166fc
&nbsp;
&gt;&gt; evt.<span style="color: #0000FF;">get</span>
	<span style="color: #0000FF;">Class</span> = <span style="color: #080;">&#91;</span> <span style="color: #080;">&#40;</span><span style="color: #33f;">1</span> by <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> java.<span style="">lang</span>.<span style="color: #0000FF;">Class</span> array<span style="color: #080;">&#93;</span>
	TestEventCallback = 
	TestEventCallbackData = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
&nbsp;
	BeingDeleted = off
	ButtonDownFcn = 
	Children = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
	Clipping = on
	CreateFcn = 
	DeleteFcn = 
	BusyAction = queue
	HandleVisibility = on
	HitTest = on
	Interruptible = on
	Parent = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
	Selected = off
	SelectionHighlight = on
	Tag = 
	<span style="color: #0000FF;">Type</span> = EventTest
	<span style="color: #0000FF;">UIContextMenu</span> = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
	UserData = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
	Visible = on
&nbsp;
&gt;&gt; <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>evt<span style="color: #080;">&#41;</span>
	<span style="color: #0000FF;">Class</span>
	TestEventCallback<span style="color: #F0F;">:</span> string -or- <span style="color: #0000FF;">function</span> handle -or- <span style="color: #0000FF;">cell</span> array
	<span style="color: #F0F;">...</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>evt,<span style="color:#A020F0;">'TestEventCallback'</span>,@<span style="color: #080;">&#40;</span>h,e<span style="color: #080;">&#41;</span><span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>h<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>evt<span style="color: #080;">&#41;</span>
	<span style="color: #0000FF;">Class</span> = <span style="color: #080;">&#91;</span> <span style="color: #080;">&#40;</span><span style="color: #33f;">1</span> by <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> java.<span style="">lang</span>.<span style="color: #0000FF;">Class</span> array<span style="color: #080;">&#93;</span>
	TestEventCallback = <span style="color: #080;">&#91;</span> <span style="color: #080;">&#40;</span><span style="color: #33f;">1</span> by <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> function_handle array<span style="color: #080;">&#93;</span>   &lt;= ok
	TestEventCallbackData = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
	<span style="color: #F0F;">...</span>
&nbsp;
&gt;&gt; evt.<span style="">notifyMyTest</span>   <span style="color: #228B22;">% invoke Java event</span>
              <span style="color: #33f;">0.0009765625</span>   <span style="color: #228B22;">% &lt;= Matlab callback</span></pre></div></div><p>Note how Matlab automatically converted the Java event testEvent, declared in interface MyTestListener, into a Matlab callback TestEventCallback (the first character is always capitalized). All Java events are automatically converted in this fashion, by appending a &#8216;Callback&#8217; suffix. Here is a code snippet from R2008a&#8217;s \toolbox\matlab\uitools\@opaque\addlistener.m that shows this (slightly edited):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">hSrc = handle<span style="color: #080;">&#40;</span>jobj,<span style="color:#A020F0;">'callbackproperties'</span><span style="color: #080;">&#41;</span>;
allfields = <span style="color: #0000FF;">sortrows</span><span style="color: #080;">&#40;</span>fields<span style="color: #080;">&#40;</span><span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hSrc<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">for</span> <span style="color: #0000FF;"><span style="color: #33f;">i</span></span> = <span style="color: #33f;">1</span><span style="color: #F0F;">:</span><span style="color: #0000FF;">length</span><span style="color: #080;">&#40;</span>allfields<span style="color: #080;">&#41;</span>
   fn = allfields<span style="color: #080;">&#123;</span><span style="color: #0000FF;"><span style="color: #33f;">i</span></span><span style="color: #080;">&#125;</span>;
   <span style="color: #0000FF;">if</span> ~<span style="color: #0000FF;">isempty</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">findstr</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Callback'</span>,fn<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
      <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">strrep</span><span style="color: #080;">&#40;</span>fn,<span style="color:#A020F0;">'Callback'</span>,<span style="color:#A020F0;">''</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
   <span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">end</span>
&nbsp;
callback = @<span style="color: #080;">&#40;</span>o,e<span style="color: #080;">&#41;</span> cbBridge<span style="color: #080;">&#40;</span>o,e,response<span style="color: #080;">&#41;</span>;
hdl = <span style="color: #0000FF;">handle.<span style="">listener</span></span><span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span>jobj<span style="color: #080;">&#41;</span>, eventName, callback<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">function</span> cbBridge<span style="color: #080;">&#40;</span>o,e,response<span style="color: #080;">&#41;</span>
   hgfeval<span style="color: #080;">&#40;</span>response, java<span style="color: #080;">&#40;</span>o<span style="color: #080;">&#41;</span>, e.<span style="">JavaEvent</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">end</span></pre></div></div><p>Note that <i><b>hgfeval</b></i>, which is used within the cbBridge callback function, is a semi-documented pure-Matlab built-in function, which I <a
target="_blank" href="http://UndocumentedMatlab.com/blog/hgfeval/">described</a> a few weeks ago.</p><p>If several events have the same case-insensitive name, then the additional callbacks will have an appended underscore character (e.g., &#8216;TestEventCallback_&#8217;):</p><div
class="wp_syntax"><div
class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// In the Java class:</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> MyTestListener <span style="color: #000000; font-weight: bold;">extends</span> java.<span style="color: #006633;">util</span>.<span style="color: #003399;">EventListener</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">void</span> testEvent<span style="color: #009900;">&#40;</span>MyTestEvent e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">void</span> testevent<span style="color: #009900;">&#40;</span>TestEvent2 e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% …and back in Matlab:</span>
&gt;&gt; evt=EventTest; evt.<span style="color: #0000FF;">get</span>
	<span style="color: #0000FF;">Class</span> = <span style="color: #080;">&#91;</span> <span style="color: #080;">&#40;</span><span style="color: #33f;">1</span> by <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> java.<span style="">lang</span>.<span style="color: #0000FF;">Class</span> array<span style="color: #080;">&#93;</span>
	TestEventCallback = 
	TestEventCallbackData = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
	TestEventCallback_ = 
	TestEventCallback_Data = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span> 
	<span style="color: #F0F;">...</span></pre></div></div><p>To complete this discussion, it should be noted that Matlab also automatically defines corresponding Events in the Java object’s <i><b>classhandle</b></i>. Unfortunately, <i><b>classhandle</b></i> events are not differentiated in a similar manner – in this case only a single event is created, named Testevent. <i><b>classhandle</b></i> events, and their relationship to the preceding discussion, will be described in Donn Scull&#8217;s upcoming series on UDD.</p><p>An alternative to using callbacks on Java events, as shown above, is to use undocumented <a
target="_blank" href="http://UndocumentedMatlab.com/blog/continuous-slider-callback/#Event_Listener"><i><b>handle.listener</b></i>s</a>:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">hListener = <span style="color: #0000FF;">handle.<span style="">listener</span></span><span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span>evt<span style="color: #080;">&#41;</span>,<span style="color:#A020F0;">'TestEvent'</span>,callback<span style="color: #080;">&#41;</span>;</pre></div></div><p>There are several other odds and ends, but this article should be sufficient for implementing a fully-functional Java event handling mechanism in Matlab. Good luck!</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/udd-events-and-listeners/' rel='bookmark' title='UDD Events and Listeners'>UDD Events and Listeners</a> <small>UDD event listeners can be used to listen to property value changes and other important events of Matlab objects...</small></li><li><a
href='http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool-callbacks/' rel='bookmark' title='uisplittool &amp; uitogglesplittool callbacks'>uisplittool &#038; uitogglesplittool callbacks</a> <small>Matlab's undocumented uisplittool and uitogglesplittool are powerful toolbar controls - this article explains how to customize their behavior...</small></li><li><a
href='http://undocumentedmatlab.com/blog/udd-and-java/' rel='bookmark' title='UDD and Java'>UDD and Java</a> <small>UDD provides built-in convenience methods to facilitate the integration of Matlab UDD objects with Java code - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/uicontrol-callbacks/' rel='bookmark' title='Uicontrol callbacks'>Uicontrol callbacks</a> <small>This post details undocumented callbacks exposed by the underlying Java object of Matlab uicontrols, that can be used to modify the control's behavior in a multitude of different events...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/feed/</wfw:commentRss> <slash:comments>26</slash:comments> </item> <item><title>The hgfeval function</title><link>http://undocumentedmatlab.com/blog/hgfeval/</link> <comments>http://undocumentedmatlab.com/blog/hgfeval/#comments</comments> <pubDate>Wed, 27 Oct 2010 18:00:59 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Semi-documented function]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[Pure Matlab]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=1925</guid> <description><![CDATA[The semi-documented hgfeval function can be useful for callback chaining - this article explains how<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/javacomponent/' rel='bookmark' title='The javacomponent function'>The javacomponent function</a> <small>Matlab's built-in javacomponent function can be used to display Java components in Matlab application - this article details its usages and limitations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/undocumented-feature-function/' rel='bookmark' title='Undocumented feature() function'>Undocumented feature() function</a> <small>Matlab's undocumented feature function enables access to some internal experimental features...</small></li><li><a
href='http://undocumentedmatlab.com/blog/ismembc-undocumented-helper-function/' rel='bookmark' title='ismembc &#8211; undocumented helper function'>ismembc &#8211; undocumented helper function</a> <small>Matlab has several undocumented internal helper functions that can be useful on their own in some cases. This post presents the ismembc function....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>Last week&#8217;s article about <a
target="_blank" href="http://UndocumentedMatlab.com/blog/matlab-java-interface-using-static-control/">using a static GUI control</a>, made use of the <i><b>hgfeval</b></i> function for its callback switch-yard dispatching. Today&#8217;s article will expose this important but often overlooked function.</p><p><i><b>hgfeval</b></i> is a built-in <a
target="_blank" href="http://UndocumentedMatlab.com/blog/legend-semi-documented-feature/#Semi-documented">semi-documented</a> function. This means that the function is explained in a comment within the hgfeval.m file (which can be seen via the <i><b>edit</b></i>(&#8216;hgfeval&#8217;) command), that is nonetheless not part of the official help or doc sections. It is an unsupported function originally intended only for internal Matlab use, which of course doesn&#8217;t mean we can&#8217;t use it. <i><b>hgfeval</b></i> is currently used extensively within the Matlab code-base.</p><h3 id="Chaining">Callback chaining</h3><p><i><b>hgfeval</b></i>&#8216;s main purpose is to programmatically (synchronously) invoke a callback, rather than it being dynamically (a-synchronously) invoked when some event occurs. This need often occurs when <a
target="_blank" href="http://UndocumentedMatlab.com/blog/inactive-control-tooltips-event-chaining/">chaining events</a>. In a nutshell, we need to programmatically invoke Callback A (an executable code [=string], function handle, or cell array of function handle with extra parameters) within our code, which is typically located in another callback (B). For example:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> CallbackB<span style="color: #080;">&#40;</span>hObject, hEventData, <span style="color: #0000FF;">varargin</span><span style="color: #080;">&#41;</span>
    callbackA = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span>, <span style="color:#A020F0;">'ButtonDownFcn'</span><span style="color: #080;">&#41;</span>;
    hgfeval<span style="color: #080;">&#40;</span>callbackA<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p><i><b>hgfeval</b></i> is important when we want to force the objects passed as the callback&#8217;s first two input parameters (hObject and hEventData): <i><b>hgfeval</b></i> pre-pends all its extra parameters (arguments #2+) to the callback&#8217;ed function. So, calling <i><b>hgfeval</b></i>({@myFunc,arg1,arg2}, argA, argB) will actually invoke <i>myFunc</i>(argA,argB,arg1,arg2). Using this syntax we guaranty that whatever the invoked callback may be, its initial arguments will always be set to the necessary argA,argB.</p><p>This is often used in what MathWorks calls a callback-bridge. For example, in the following example we set the cbBridge function as a callback bridge for myCallback, that forces <i><b>java</b></i>(o) as the reference object (the invoked callback&#8217;s first argument) and e.JavaEvent as the second arg; all user args will then follow as optional additional args:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">hdl = <span style="color: #0000FF;">handle.<span style="">listener</span></span><span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span>jobj<span style="color: #080;">&#41;</span>, eventName, <span style="color: #F0F;">...</span>
                      @<span style="color: #080;">&#40;</span>o,e<span style="color: #080;">&#41;</span>cbBridge<span style="color: #080;">&#40;</span>o,e,@myCallback<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">function</span> cbBridge<span style="color: #080;">&#40;</span>o,e,myCallback<span style="color: #080;">&#41;</span>
    hgfeval<span style="color: #080;">&#40;</span>myCallback, java<span style="color: #080;">&#40;</span>o<span style="color: #080;">&#41;</span>, e.<span style="">JavaEvent</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">end</span></pre></div></div><p>If we had used myCallback directly, then myCallback would have been invoked with o and e rather than <i><b>java</b></i>(o) and e.JavaEvent. The point here is that using the callback bridge and <i><b>hgfeval</b></i> enabled us to tailor the parameters passed to the callback function.</p><h3 id="Compatibility">Forward &#038; backward compatibility</h3><p><i><b>hgfeval</b></i> has been built-in within all standard Matlab 7 releases, so while it may be discontinued in some future Matlab release, it did have a very long life span.</p><p>Even if for some reason this function is removed in some future Matlab release, it can easily be reproduced &#8211; after all, it only contains 35 very simple lines of pure Matlab code. In fact, for some project that had to rely on Matlab 6 (in which <i><b>hgfeval</b></i> was not yet available), it was an almost trivial task to retrofit an <i><b>hgfeval</b></i> look-alike (I had to remove function handles and similar minor tweaks):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">%% hgfeval replacement for Matlab 6 compatibility</span>
<span style="color: #0000FF;">function</span> hgfeval<span style="color: #080;">&#40;</span>fcn,<span style="color: #0000FF;">varargin</span><span style="color: #080;">&#41;</span>
    <span style="color: #0000FF;">if</span> <span style="color: #0000FF;">isempty</span><span style="color: #080;">&#40;</span>fcn<span style="color: #080;">&#41;</span>,  <span style="color: #0000FF;">return</span>;  <span style="color: #0000FF;">end</span>
    <span style="color: #0000FF;">if</span> iscell<span style="color: #080;">&#40;</span>fcn<span style="color: #080;">&#41;</span>
        <span style="color: #0000FF;">feval</span><span style="color: #080;">&#40;</span>fcn<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span>,<span style="color: #0000FF;">varargin</span><span style="color: #080;">&#123;</span><span style="color: #F0F;">:</span><span style="color: #080;">&#125;</span>,fcn<span style="color: #080;">&#123;</span><span style="color: #33f;">2</span><span style="color: #F0F;">:</span><span style="color: #0000FF;">end</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">elseif</span> <span style="color: #0000FF;">ischar</span><span style="color: #080;">&#40;</span>fcn<span style="color: #080;">&#41;</span>
        <span style="color: #0000FF;">evalin</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'base'</span>, fcn<span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">else</span>
        <span style="color: #0000FF;">feval</span><span style="color: #080;">&#40;</span>fcn,<span style="color: #0000FF;">varargin</span><span style="color: #080;">&#123;</span><span style="color: #F0F;">:</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">end</span>
<span style="color: #228B22;">%end  %no function end in Matlab 6...</span></pre></div></div><p>Have you ever used <i><b>hgfeval</b></i> in your code? If so, please share your experience in a comment <a
target="_blank" href="http://UndocumentedMatlab.com/blog/hgfeval/#respond">below</a>.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/javacomponent/' rel='bookmark' title='The javacomponent function'>The javacomponent function</a> <small>Matlab's built-in javacomponent function can be used to display Java components in Matlab application - this article details its usages and limitations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/undocumented-feature-function/' rel='bookmark' title='Undocumented feature() function'>Undocumented feature() function</a> <small>Matlab's undocumented feature function enables access to some internal experimental features...</small></li><li><a
href='http://undocumentedmatlab.com/blog/ismembc-undocumented-helper-function/' rel='bookmark' title='ismembc &#8211; undocumented helper function'>ismembc &#8211; undocumented helper function</a> <small>Matlab has several undocumented internal helper functions that can be useful on their own in some cases. This post presents the ismembc function....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/hgfeval/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Matlab-Java interface using a static control</title><link>http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/</link> <comments>http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/#comments</comments> <pubDate>Wed, 13 Oct 2010 18:15:43 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Guest bloggers]]></category> <category><![CDATA[GUI]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[Karthik Ponudurai]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=1917</guid> <description><![CDATA[The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/inactive-control-tooltips-event-chaining/' rel='bookmark' title='Inactive Control Tooltips &amp; Event Chaining'>Inactive Control Tooltips &#038; Event Chaining</a> <small>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....</small></li><li><a
href='http://undocumentedmatlab.com/blog/gui-integrated-browser-control/' rel='bookmark' title='GUI integrated browser control'>GUI integrated browser control</a> <small>A fully-capable browser component is included in Matlab and can easily be incorporated in regular Matlab GUI applications. This article shows how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/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></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><i>I would like to welcome guest blogger Karthik Ponudurai. Today, Karthik will introduce an interesting technique for interfacing Java GUI to a Matlab application.</i></p><p>The current method of interfacing Java GUI controls and Matlab is by retrieving the underlying Java callback and assigning it to a Matlab callback, as shown in the following example:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Create a Java button</span>
jButton = javacomponent<span style="color: #080;">&#40;</span>javax.<span style="">swing</span>.<span style="">JButton</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'click me'</span><span style="color: #080;">&#41;</span>, <span style="color: #F0F;">...</span>
                        <span style="color: #080;">&#91;</span><span style="color: #33f;">20</span>,<span style="color: #33f;">20</span>,<span style="color: #33f;">60</span>,<span style="color: #33f;">20</span><span style="color: #080;">&#93;</span>, <span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Assign a Matlab callback</span>
hButton = handle<span style="color: #080;">&#40;</span>jButton, <span style="color:#A020F0;">'CallbackProperties'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>jButton, <span style="color:#A020F0;">'ActionPerformedCallback'</span>, @myCallback<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Matlab callback function</span>
<span style="color: #0000FF;">function</span> myCallback<span style="color: #080;">&#40;</span>hObject, hEventData<span style="color: #080;">&#41;</span>
    <span style="color: #228B22;">% Insert your code here</span>
<span style="color: #0000FF;">end</span></pre></div></div><p>This approach works fine for simple pure-Java GUI created using an IDE (for example, <a
target="_blank" rel="nofollow" href="http://netbeans.org/">NetBeans</a> or <a
target="_blank" rel="nofollow" href="http://eclipse.org/">Eclipse</a>) that only have a small number of controls. You can retrieve all the Java controls in Matlab and set the callbacks as shown in the above example.</p><p>Unfortunately, practical GUIs often contain numerous controls. Assigning each control a different Matlab callback can be quite tedious.</p><h3 id="">Using a callback switchyard function</h3><p>A workaround to this problem can be achieved using an invisible/hidden static Java JButton. During Matlab initialization, assign a single callback for the static Java JButton:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Return a reference to the GUI's static trigger button</span>
triggerButton = statictrigger.<span style="">triggerCls</span>.<span style="">getTrigger</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Assign Matlab switchyard callback for triggerButton</span>
buttonProps = handle<span style="color: #080;">&#40;</span>triggerButton, <span style="color:#A020F0;">'callbackproperties'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>triggerButton, <span style="color:#A020F0;">'ActionPerformedCallback'</span>,@TriggerCallback<span style="color: #080;">&#41;</span>;</pre></div></div><p>When an event is triggered by any monitored control in the Java GUI, then within the Java code set the static button&#8217;s action command string to the desired Matlab callback name (a String) and invoke the static button&#8217;s <i>doClick()</i> method to trigger the Matlab TriggerCallback callback. Based on the action command string, this callback invokes the appropriate Matlab function. In this manner, Matlab&#8217;s TriggerCallback() acts as a <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/company/newsletters/news_notes/win00/prog_patterns.html">switchyard function</a> to the actual callback functions:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> TriggerCallback<span style="color: #080;">&#40;</span>hObject, hEventData<span style="color: #080;">&#41;</span>
   actionCmd = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span> hObject.<span style="">getActionCommand</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#41;</span>;
   hgfeval<span style="color: #080;">&#40;</span>actionCmd, hObject, hEventData<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>Note how the <i><b>char</b></i> function converts the Java action command (a java.lang.String object) into Matlab char array. The requested Matlab function is then dynamically invoked using Matlab&#8217;s semi-documented <a
target="_blank" href="http://undocumentedmatlab.com/blog/hgfeval/"><i><b>hgfeval</b></i> function</a>, which Yair will describe in another article later this month.</p><p>The next few sections will look into the sample application in more detail. This application can be downloaded from <a
target="_blank" href="http://UndocumentedMatlab.com/files/StaticButtonTrigger.zip">here</a>.</p><h3 id="GUI">Java GUI</h3><p>Firstly, let&#8217;s look into the Java GUI:<br
/><center><div
class="wp-caption aligncenter" style="width: 418px"><img
alt="Main Java GUI" src="http://UndocumentedMatlab.com/images/StaticButton_Java_Frame.png" title="Main Java GUI" width="408" height="325" /><p
class="wp-caption-text">Main Java GUI</p></div></center></p><p>When the &#8220;Show Result in Matlab Dialog Box&#8221; button is clicked, the form information&#8217;s (Name, Age, Sex etc&#8230;) is saved in a hash map. This hash map is then serialized to a local file (C:\streamdata). Next, the static button&#8217;s action command string is set to &#8216;show&#8217; and finally its <i>doClick()</i> method is invoked.</p><p>Below is the Java code corresponding to button click event:</p><div
class="wp_syntax"><div
class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> showActionPerformed<span style="color: #009900;">&#40;</span>java.<span style="color: #006633;">awt</span>.<span style="color: #006633;">event</span>.<span style="color: #003399;">ActionEvent</span> evt<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Add form values to hash map</span>
    hMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>name.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, name.<span style="color: #006633;">getText</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    hMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>age.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, age.<span style="color: #006633;">getValue</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    hMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>sex.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#41;</span>sex.<span style="color: #006633;">getSelectedItem</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    hMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>address.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, address.<span style="color: #006633;">getText</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    hMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>email.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, email.<span style="color: #006633;">getText</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Serialize hash map</span>
    WriteObject<span style="color: #009900;">&#40;</span>hMap<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Set trigger</span>
    triggerCls.<span style="color: #006633;">setTrigger</span><span style="color: #009900;">&#40;</span>evt.<span style="color: #006633;">getActionCommand</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div><h3 id="Matlab">Matlab callbacks</h3><p>The Java GUI sources are compiled and packaged in the statictrigger.jar file. The Matlab StaticButtonTriggerExample.m source file adds the Java library to the dynamic Java classpath:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Add dynamic java class path</span>
javaclasspath<span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span><span style="color: #0000FF;">pwd</span> <span style="color:#A020F0;">'\javalib\statictrigger.jar'</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>The main.m function contains the code for creating the Java GUI and assigning the static button callback:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% create the statictrigger object</span>
app = statictrigger.<span style="">app</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Set static trigger button listener</span>
triggerButton = statictrigger.<span style="">triggerCls</span>.<span style="">getTrigger</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
buttonProps = handle<span style="color: #080;">&#40;</span>triggerButton,<span style="color:#A020F0;">'callbackproperties'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>buttonProps,<span style="color:#A020F0;">'ActionPerformedCallback'</span>, <span style="color: #080;">&#123;</span>@StaticButtonTriggerCallback, app<span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>; 
&nbsp;
<span style="color: #228B22;">% Show the Java Frame </span>
app.<span style="">setVisible</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>statictrigger.triggerCls.<i>getTrigger()</i> is a static Java public method that returns the static button object, for which we assign our callback switchyard function.</p><p>The following is the StaticButtonTriggerCallback.m code, which displays the information in a Matlab message-box:<br
/><center><div
class="wp-caption aligncenter" style="width: 409px"><img
alt="Matlab message-box triggered by the Java GUI" src="http://UndocumentedMatlab.com/images/StaticButton_Matlab_Msgbox.png" title="Matlab message-box triggered by the Java GUI" width="399" height="133" /><p
class="wp-caption-text">Matlab message-box triggered by the Java GUI</p></div></center></p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Get action command string  </span>
actionCommand = src.<span style="">getActionCommand</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Read in serialized hash map</span>
hashMap = app.<span style="">ReadObject</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Convert hash map to Matlab structure     </span>
data = Hash2Struct<span style="color: #080;">&#40;</span>hashMap<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Display data in Matlab dialog box</span>
msg = <span style="color: #080;">&#91;</span><span style="color:#A020F0;">'Name: '</span> <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>hashMap.<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'name'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #F0F;">...</span>
       <span style="color:#A020F0;">', Age: '</span> <span style="color: #0000FF;">num2str</span><span style="color: #080;">&#40;</span>hashMap.<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'age'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #F0F;">...</span>
       <span style="color:#A020F0;">', Sex: '</span> <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>hashMap.<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'sex'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #F0F;">...</span>
       <span style="color:#A020F0;">', Address: '</span> <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>hashMap.<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'address'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #F0F;">...</span>
       <span style="color:#A020F0;">', Email: '</span> <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>hashMap.<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'email'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#93;</span>;
uiwait<span style="color: #080;">&#40;</span><span style="color: #0000FF;">helpdlg</span><span style="color: #080;">&#40;</span>msg, <span style="color:#A020F0;">'Form Details'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>You can download the example&#8217;s files from <a
target="_blank" href="http://UndocumentedMatlab.com/files/StaticButtonTrigger.zip">here</a>. Extract the zip file, <i><b>cd</b></i> to the newly-generated StaticButtonTrigger folder, then invoke the StaticButtonTriggerExample.m function to run the example.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/inactive-control-tooltips-event-chaining/' rel='bookmark' title='Inactive Control Tooltips &amp; Event Chaining'>Inactive Control Tooltips &#038; Event Chaining</a> <small>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....</small></li><li><a
href='http://undocumentedmatlab.com/blog/gui-integrated-browser-control/' rel='bookmark' title='GUI integrated browser control'>GUI integrated browser control</a> <small>A fully-capable browser component is included in Matlab and can easily be incorporated in regular Matlab GUI applications. This article shows how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/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></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/feed/</wfw:commentRss> <slash:comments>17</slash:comments> </item> <item><title>Accessing plot brushed data</title><link>http://undocumentedmatlab.com/blog/accessing-plot-brushed-data/</link> <comments>http://undocumentedmatlab.com/blog/accessing-plot-brushed-data/#comments</comments> <pubDate>Wed, 06 Oct 2010 18:00:45 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Figure window]]></category> <category><![CDATA[Handle graphics]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[Menubar]]></category> <category><![CDATA[Pure Matlab]]></category> <category><![CDATA[scribe]]></category> <category><![CDATA[UIInspect]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=1911</guid> <description><![CDATA[Plot data brushing can be accessed programmatically using very simple pure-Matlab code<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/controlling-plot-data-tips/' rel='bookmark' title='Controlling plot data-tips'>Controlling plot data-tips</a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li><li><a
href='http://undocumentedmatlab.com/blog/accessing-the-matlab-editor/' rel='bookmark' title='Accessing the Matlab Editor'>Accessing the Matlab Editor</a> <small>The Matlab Editor can be accessed programmatically, for a wide variety of possible uses - this article shows how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/plot-liminclude-properties/' rel='bookmark' title='Plot LimInclude properties'>Plot LimInclude properties</a> <small>The plot objects' XLimInclude, YLimInclude, ZLimInclude, ALimInclude and CLimInclude properties are an important feature, that has both functional and performance implications....</small></li><li><a
href='http://undocumentedmatlab.com/blog/undocumented-scatter-plot-behavior/' rel='bookmark' title='Undocumented scatter plot behavior'>Undocumented scatter plot behavior</a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>A few days ago, a reader of the Matlab Desktop blog <a
target="_blank" rel="nofollow" href="http://blogs.mathworks.com/desktop/2008/05/12/brush-up-on-your-data/#comment-7364">asked</a> whether it is possible to store plot brushed data in a separate variable for later processing. <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/data_analysis/brh7_p3-1.html#brh7_p3-3">Data Brushing</a>, first introduced in R2008a, enables interactive selection and marking of plot data points. The brushed data can then be stored in a variable using the context (right-click) menu, or the figure&#8217;s Tools/Brushing menu.</p><p><center><div
class="wp-caption aligncenter" style="width: 460px"><img
alt="Saving brushed data to a variable" src="http://UndocumentedMatlab.com/images/Brushing1b.png" title="Saving brushed data to a variable" width="450" height="325" /><p
class="wp-caption-text">Saving brushed data to a variable</p></div></center></p><p>The said reader has specifically wanted programmatic access, rather than interactivity. The official answer is that data brushing was designed to be an interactive tool, and so this cannot be done. However, this has never stopped us before. So off I went to launch my favorite inspection tool, the <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect-display-methods-properties-callbacks-of-an-object">UIInspect utility</a> on the figure above (UIInspect will be described in a near-future article), which can be recreated with the following simple code:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">t=<span style="color: #33f;">0</span><span style="color: #F0F;">:</span><span style="color: #33f;">0.2</span><span style="color: #F0F;">:</span><span style="color: #33f;">25</span>; <span style="color: #0000FF;">plot</span><span style="color: #080;">&#40;</span>t,<span style="color: #0000FF;">sin</span><span style="color: #080;">&#40;</span>t<span style="color: #080;">&#41;</span>,<span style="color:#A020F0;">'.-'</span><span style="color: #080;">&#41;</span>;
<span style="color: #228B22;">% Now brush some data points...</span>
uiinspect<span style="color: #080;">&#40;</span><span style="color: #0000FF;">gca</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 460px"><a
target="_blank" href="http://UndocumentedMatlab.com/images/Brushing2a.png"><img
alt="UIInspect-ion of a data-brushed plot" src="http://UndocumentedMatlab.com/images/Brushing2a.png" title="UIInspect-ion of a data-brushed plot" width="450" height="389" /></a><p
class="wp-caption-text">UIInspect-ion of a data-brushed plot (click for details)</p></div></center></p><p>A couple of alternative answers to the reader&#8217;s question were immediately apparent:</p><h3 id="data">Directly accessing brushed data</h3><p>First, we notice that data brushing added data-brushing context menus, both of which are called <i>BrushSeriesContextMenu</i> (the duplication is an internal Matlab bug, that does not affect usability as far as I can tell).</p><p>Also, an invisible scribe overlay axes has been added to hold the new annotations (data brushing is considered an annotation; scribe axes deserve a separate article, which they will indeed get someday).</p><p>More importantly for our needs, we see a new <i><b>line</b></i> item called &#8216;Brushing&#8217;, which displays the red lines and data points that we seek. We can now easily get the brushed data using this line&#8217;s <b>XData</b> and <b>YData</b> properties: <u>non</u>-brushed data points simply have NaN values:</p><p><center><div
class="wp-caption aligncenter" style="width: 460px"><img
alt="UIInspect-ion of the data-brushing line" src="http://UndocumentedMatlab.com/images/Brushing2b.png" title="UIInspect-ion of the data-brushing line" width="450" height="325" /><p
class="wp-caption-text">UIInspect-ion of the data-brushing line</p></div></center></p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">hBrushLine = findall<span style="color: #080;">&#40;</span><span style="color: #0000FF;">gca</span>,<span style="color:#A020F0;">'tag'</span>,<span style="color:#A020F0;">'Brushing'</span><span style="color: #080;">&#41;</span>;
brushedData = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>hBrushLine, <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'Xdata'</span>,<span style="color:#A020F0;">'Ydata'</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
brushedIdx = ~<span style="color: #0000FF;">isnan</span><span style="color: #080;">&#40;</span>brushedData<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
brushedXData = brushedData<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#40;</span>brushedIdx<span style="color: #080;">&#41;</span>;
brushedYData = brushedData<span style="color: #080;">&#123;</span><span style="color: #33f;">2</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#40;</span>brushedIdx<span style="color: #080;">&#41;</span>;
<span style="color: #228B22;">% and similarly for ZData in 3D plots</span></pre></div></div><h3 id="callbacks">Accessing brushing callbacks</h3><p>Yet another way of approaching the problem is to use the available callback functions built-into the data-brushing functionality. We can access either the <i>BrushSeriesContextMenu</i> or the figure&#8217;s Tools/Brushing menu. I will leave the former (context-menu) approach as an exercise to the reader, and just describe the figure&#8217;s menu approach.</p><p>As I have already explained in a <a
target="_blank" href="http://undocumentedmatlab.com/blog/modifying-default-toolbar-menubar-actions/">dedicated article</a>, figure menu-bar actions are accessible via their handles, and we can retrieve that using a unique tag (well, most of the time &#8211; read that article for details). In our case, the Tools/Brushing/Create-new-variable menu item has the unique tag &#8216;figDataManagerNewVar&#8217;. So let&#8217;s use it:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; hNewVarMenuItem = findall<span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span>,<span style="color:#A020F0;">'tag'</span>,<span style="color:#A020F0;">'figDataManagerNewVar'</span><span style="color: #080;">&#41;</span>
hNewVarMenuItem =
          <span style="color: #33f;">742.000244140625</span>
&nbsp;
&gt;&gt; hNewVarCallback = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>hNewVarMenuItem,<span style="color:#A020F0;">'callback'</span><span style="color: #080;">&#41;</span>
hNewVarCallback = 
    @datamanager.<span style="">newvar</span>
&nbsp;
&gt;&gt; hNewVarCallback<span style="color: #080;">&#40;</span><span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span>   <span style="color: #228B22;">% activate the callback</span>
<span style="color: #228B22;">% =&gt; set 'ans' as the new variable holding the brushed data</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">ans</span>
<span style="color: #0000FF;">ans</span> =
                       <span style="color: #33f;">6.4</span>         <span style="color: #33f;">0.116549204850494</span>
                       <span style="color: #33f;">6.6</span>         <span style="color: #33f;">0.311541363513379</span>
                       <span style="color: #33f;">6.8</span>         <span style="color: #33f;">0.494113351138609</span>
                         <span style="color: #33f;">7</span>         <span style="color: #33f;">0.656986598718789</span>
                       <span style="color: #33f;">7.2</span>         <span style="color: #33f;">0.793667863849153</span>
                       <span style="color: #33f;">7.4</span>         <span style="color: #33f;">0.898708095811627</span>
                       <span style="color: #33f;">7.6</span>         <span style="color: #33f;">0.967919672031486</span>
                       <span style="color: #33f;">7.8</span>         <span style="color: #33f;">0.998543345374605</span>
                       <span style="color: #F0F;">...</span>         <span style="color: #F0F;">...</span></pre></div></div><p>Of course, we could also have gone the hard way, via the scribe axes and the annotations route. For masochistic people like me it could even be a worthwhile challenge. But for all other normal people, why bother when there are such simple alternatives, if we only knew how to find them. <img
src='http://undocumentedmatlab.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /></p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/controlling-plot-data-tips/' rel='bookmark' title='Controlling plot data-tips'>Controlling plot data-tips</a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li><li><a
href='http://undocumentedmatlab.com/blog/accessing-the-matlab-editor/' rel='bookmark' title='Accessing the Matlab Editor'>Accessing the Matlab Editor</a> <small>The Matlab Editor can be accessed programmatically, for a wide variety of possible uses - this article shows how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/plot-liminclude-properties/' rel='bookmark' title='Plot LimInclude properties'>Plot LimInclude properties</a> <small>The plot objects' XLimInclude, YLimInclude, ZLimInclude, ALimInclude and CLimInclude properties are an important feature, that has both functional and performance implications....</small></li><li><a
href='http://undocumentedmatlab.com/blog/undocumented-scatter-plot-behavior/' rel='bookmark' title='Undocumented scatter plot behavior'>Undocumented scatter plot behavior</a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/accessing-plot-brushed-data/feed/</wfw:commentRss> <slash:comments>8</slash:comments> </item> <item><title>Advanced JIDE Property Grids</title><link>http://undocumentedmatlab.com/blog/advanced-jide-property-grids/</link> <comments>http://undocumentedmatlab.com/blog/advanced-jide-property-grids/#comments</comments> <pubDate>Thu, 22 Apr 2010 06:01:19 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <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[Undocumented feature]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[Internal component]]></category> <category><![CDATA[JIDE]]></category> <category><![CDATA[Levente Hunyadi]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=1316</guid> <description><![CDATA[JIDE property grids can use complex cell renderer and editor components and can signal property change events asynchronously to Matlab callbacks<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/jide-property-grids/' rel='bookmark' title='JIDE Property Grids'>JIDE Property Grids</a> <small>The JIDE components pre-bundled in Matlab enable creating user-customized property grid tables...</small></li><li><a
href='http://undocumentedmatlab.com/blog/plot-linesmoothing-property/' rel='bookmark' title='Plot LineSmoothing property'>Plot LineSmoothing property</a> <small>LineSmoothing is a hidden and undocumented plot line property that creates anti-aliased (smooth unpixelized) lines in Matlab plots...</small></li><li><a
href='http://undocumentedmatlab.com/blog/axes-looseinset-property/' rel='bookmark' title='Axes LooseInset property'>Axes LooseInset property</a> <small>Matlab plot axes have an undocumented LooseInset property that sets empty margins around the axes, and can be set to provide a tighter fit of the axes to their surroundings....</small></li><li><a
href='http://undocumentedmatlab.com/blog/date-selection-components/' rel='bookmark' title='Date selection components'>Date selection components</a> <small>The JIDE package, pre-bundled in Matlab, contains several GUI controls for selecting dates - this article explains how they can be used...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><i>Once again, I would like to welcome guest blogger <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/60898">Levente Hunyadi</a>.</i></p><h3 id="renderers">Non-standard property renderers and editors</h3><p>Last week, I discussed JIDE&#8217;s property table and showed how we can add custom properties and present this table in our Matlab GUI. Today, I will extend the previous week&#8217;s example to include more sophisticated renderers and editors.</p><p><a
target="_blank" rel="nofollow" href="http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editrender">Cell renderers and editors</a> are the backbone of JTable implementations, JIDE&#8217;s property grid included. Each property is associated with a type, and a renderer and an editor may be registered for a type. The cell renderer controls how the property value is displayed, while the editor determines how it is edited. For example, flags (Java <em>Boolean</em>s) are often both rendered and edited using a checkbox, but can also use a text renderer with a combo-box editor. <em>PropertyTable</em> automatically assigns a default renderer and editor to each property, based on its type: Flags are assigned a combo-box editor of true/false values, and similarly for other types.</p><p>Let us now modify the preassigned editor. First, let&#8217;s set a <a
target="_blank" rel="nofollow" href="http://java.sun.com/docs/books/tutorial/uiswing/components/button.html#checkbox">checkbox</a> editor (<a
target="_blank" rel="nofollow" href="http://www.jidesoft.com/javadoc/com/jidesoft/grid/BooleanCheckBoxCellEditor.html"><em>BooleanCheckBoxCellEditor</em></a>) for flags and a <a
target="_blank" rel="nofollow" href="http://java.sun.com/docs/books/tutorial/uiswing/components/spinner.html">spinner</a> for numbers:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Initialize JIDE's usage within Matlab</span>
com.<span style="">mathworks</span>.<span style="">mwswing</span>.<span style="">MJUtilities</span>.<span style="">initJIDE</span>;
&nbsp;
<span style="color: #228B22;">% Prepare the properties list:</span>
<span style="color: #228B22;">% First two logical values (flags)</span>
list = java.<span style="">util</span>.<span style="">ArrayList</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
prop1 = com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">DefaultProperty</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
prop1.<span style="">setName</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'mylogical'</span><span style="color: #080;">&#41;</span>;
prop1.<span style="">setType</span><span style="color: #080;">&#40;</span>javaclass<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'logical'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
prop1.<span style="">setValue</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">true</span><span style="color: #080;">&#41;</span>;
list.<span style="">add</span><span style="color: #080;">&#40;</span>prop1<span style="color: #080;">&#41;</span>;
&nbsp;
prop2 = com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">DefaultProperty</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
prop2.<span style="">setName</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'mycheckbox'</span><span style="color: #080;">&#41;</span>;
prop2.<span style="">setType</span><span style="color: #080;">&#40;</span>javaclass<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'logical'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
prop2.<span style="">setValue</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">true</span><span style="color: #080;">&#41;</span>;
prop2.<span style="">setEditorContext</span><span style="color: #080;">&#40;</span>com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">BooleanCheckBoxCellEditor</span>.<span style="">CONTEXT</span><span style="color: #080;">&#41;</span>;
list.<span style="">add</span><span style="color: #080;">&#40;</span>prop2<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Now integers (note the different way to set property values):</span>
prop3 = com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">DefaultProperty</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
javatype = javaclass<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'int32'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>prop3,<span style="color:#A020F0;">'Name'</span>,<span style="color:#A020F0;">'myinteger'</span>,<span style="color:#A020F0;">'Type'</span>,javatype,<span style="color:#A020F0;">'Value'</span>,<span style="color: #0000FF;">int32</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
list.<span style="">add</span><span style="color: #080;">&#40;</span>prop3<span style="color: #080;">&#41;</span>;
&nbsp;
prop4 = com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">DefaultProperty</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>prop4,<span style="color:#A020F0;">'Name'</span>,<span style="color:#A020F0;">'myspinner'</span>,<span style="color:#A020F0;">'Type'</span>,javatype,<span style="color:#A020F0;">'Value'</span>,<span style="color: #0000FF;">int32</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>prop4,<span style="color:#A020F0;">'EditorContext'</span>,com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">SpinnerCellEditor</span>.<span style="">CONTEXT</span><span style="color: #080;">&#41;</span>;
list.<span style="">add</span><span style="color: #080;">&#40;</span>prop4<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Prepare a properties table containing the list</span>
model = com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">PropertyTableModel</span><span style="color: #080;">&#40;</span>list<span style="color: #080;">&#41;</span>;
model.<span style="">expandAll</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">grid</span> = com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">PropertyTable</span><span style="color: #080;">&#40;</span>model<span style="color: #080;">&#41;</span>;
pane = com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">PropertyPane</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">grid</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Display the properties pane onscreen</span>
hFig = <span style="color: #0000FF;">figure</span>;
panel = uipanel<span style="color: #080;">&#40;</span>hFig<span style="color: #080;">&#41;</span>;
javacomponent<span style="color: #080;">&#40;</span>pane, <span style="color: #080;">&#91;</span><span style="color: #33f;">0</span> <span style="color: #33f;">0</span> <span style="color: #33f;">200</span> <span style="color: #33f;">200</span><span style="color: #080;">&#93;</span>, panel<span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 310px"><img
alt="A property grid with checkbox and spinner controls" src="http://UndocumentedMatlab.com/images/PropertyGrid_types.png" title="A property grid with checkbox and spinner controls" width="200" height="165" /><p
class="wp-caption-text">A property grid with checkbox and spinner controls</p></div></center></p><p>Notice how the <b>EditorContext</b> is used to specify a non-standard renderer/editor for myspinner and mycheckbox: The mylogical flag displays as a string label, while mycheckbox displays as a checkbox; myinteger uses a regular integer editor that accepts whole numbers, while myspinner uses a spinner control to modify the value.</p><p>Note that instead of creating an entirely new properties list and table, we could have run last week&#8217;s example, modified <em>list</em> and then simply called <em>model.refresh()</em> to update the display.</p><p>Also note that Matlab types are automatically converted to Java types, but we must be careful that the results of the conversion should match our <em>setType</em> declaration. The logical value <i><b>true</b></i> converts to <em>java.lang.Boolean</em>, but 1 by default would be a double, which is the standard numeric type in Matlab. The <i><b>int32</b></i> wrapper is needed to force a conversion to a <em>java.lang.Integer</em>.</p><p>Spinners with indefinite value bounds are seldom useful. The following shows how to register a new editor to restrict values to a fixed range. Remember to unregister the editor when it is no longer used:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">javatype = javaclass<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'int32'</span><span style="color: #080;">&#41;</span>;
value  = <span style="color: #0000FF;">int32</span><span style="color: #080;">&#40;</span><span style="color: #33f;">0</span><span style="color: #080;">&#41;</span>;
minVal = <span style="color: #0000FF;">int32</span><span style="color: #080;">&#40;</span>-<span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>;
maxVal = <span style="color: #0000FF;">int32</span><span style="color: #080;">&#40;</span><span style="color: #33f;">5</span><span style="color: #080;">&#41;</span>;
step   = <span style="color: #0000FF;">int32</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
spinner = javax.<span style="">swing</span>.<span style="">SpinnerNumberModel</span><span style="color: #080;">&#40;</span>value, minVal, maxVal, step<span style="color: #080;">&#41;</span>;
editor = com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">SpinnerCellEditor</span><span style="color: #080;">&#40;</span>spinner<span style="color: #080;">&#41;</span>;
context = com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">EditorContext</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'spinnereditor'</span><span style="color: #080;">&#41;</span>;
com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">CellEditorManager</span>.<span style="">registerEditor</span><span style="color: #080;">&#40;</span>javatype, editor, context<span style="color: #080;">&#41;</span>;
&nbsp;
prop = com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">DefaultProperty</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>prop, <span style="color:#A020F0;">'Name'</span>,<span style="color:#A020F0;">'myspinner'</span>, <span style="color:#A020F0;">'Type'</span>,javatype, <span style="color: #F0F;">...</span>
          <span style="color:#A020F0;">'Value'</span>,<span style="color: #0000FF;">int32</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>, <span style="color:#A020F0;">'EditorContext'</span>,context<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% [do something useful here...]</span>
&nbsp;
com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">CellEditorManager</span>.<span style="">unregisterEditor</span><span style="color: #080;">&#40;</span>javatype, context<span style="color: #080;">&#41;</span>;</pre></div></div><p>The principle is the same for <a
target="_blank" rel="nofollow" href="http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html">combo-boxes</a>:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">javatype = javaclass<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'char'</span>, <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
options = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'spring'</span>, <span style="color:#A020F0;">'summer'</span>, <span style="color:#A020F0;">'fall'</span>, <span style="color:#A020F0;">'winter'</span><span style="color: #080;">&#125;</span>;
editor = com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">ListComboBoxCellEditor</span><span style="color: #080;">&#40;</span>options<span style="color: #080;">&#41;</span>;
context = com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">EditorContext</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'comboboxeditor'</span><span style="color: #080;">&#41;</span>;
com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">CellEditorManager</span>.<span style="">registerEditor</span><span style="color: #080;">&#40;</span>javatype, editor, context<span style="color: #080;">&#41;</span>;
&nbsp;
prop = com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">DefaultProperty</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>prop, <span style="color:#A020F0;">'Name'</span>,<span style="color:#A020F0;">'season'</span>, <span style="color:#A020F0;">'Type'</span>,javatype, <span style="color: #F0F;">...</span>
          <span style="color:#A020F0;">'Value'</span>,<span style="color:#A020F0;">'spring'</span>, <span style="color:#A020F0;">'EditorContext'</span>,context<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% [do something useful here...]</span>
&nbsp;
com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">CellEditorManager</span>.<span style="">unregisterEditor</span><span style="color: #080;">&#40;</span>javatype, context<span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 260px"><img
alt="A property grid with a combobox control" src="http://UndocumentedMatlab.com/images/PropertyGrid_combobox.png" title="A property grid with a combobox control" width="200" height="165" /><p
class="wp-caption-text">A property grid with a combobox control</p></div></center></p><h3 id="nested">Nested properties</h3><p>Properties can act as a parent node for other properties. A typical example is an object&#8217;s dimensions: a parent node value may be edited as a 2-by-1 matrix, but width and height may also be exposed individually. Nested properties are created as regular properties. However, rather than adding them directly to a <em>PropertyTableModel</em>, they are added under a <em>Property</em> instance using its <em>addChild</em> method:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">propdimensions = com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">DefaultProperty</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
propdimensions.<span style="">setName</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'dimensions'</span><span style="color: #080;">&#41;</span>;
propdimensions.<span style="">setEditable</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">false</span><span style="color: #080;">&#41;</span>;
&nbsp;
propwidth = com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">DefaultProperty</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
propwidth.<span style="">setName</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'width'</span><span style="color: #080;">&#41;</span>;
propwidth.<span style="">setType</span><span style="color: #080;">&#40;</span>javaclass<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'int32'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
propwidth.<span style="">setValue</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">int32</span><span style="color: #080;">&#40;</span><span style="color: #33f;">100</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
propdimensions.<span style="">addChild</span><span style="color: #080;">&#40;</span>propwidth<span style="color: #080;">&#41;</span>;
&nbsp;
propheight = com.<span style="">jidesoft</span>.<span style="color: #0000FF;">grid</span>.<span style="">DefaultProperty</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
propheight.<span style="">setName</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'height'</span><span style="color: #080;">&#41;</span>;
propheight.<span style="">setType</span><span style="color: #080;">&#40;</span>javaclass<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'int32'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
propheight.<span style="">setValue</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">int32</span><span style="color: #080;">&#40;</span><span style="color: #33f;">100</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
propdimensions.<span style="">addChild</span><span style="color: #080;">&#40;</span>propheight<span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 210px"><img
alt="A property grid with nested property" src="http://UndocumentedMatlab.com/images/PropertyGrid_nested.png" title="A property grid with nested property" width="200" height="165" /><p
class="wp-caption-text">A property grid with nested property</p></div></center></p><p><em>PropertyTableModel</em> accesses properties in a hierarchical naming scheme. This means that the parts of nested properties are separated with a dot (.). In the above example, these two fully-qualified names are <em>dimensions.width</em> and <em>dimensions.height</em>.</p><h3 id="callback">Trapping property change events</h3><p>Sometimes it is desirable to subscribe to the PropertyChange event. This event is fired by <em>PropertyTableModel</em> whenever any property value is updated. To expose Java events to Matlab, we use the two-parameter form of the <i><b>handle</b></i> function with the optional CallbackProperties parameter.</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">hModel = handle<span style="color: #080;">&#40;</span>model, <span style="color:#A020F0;">'CallbackProperties'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hModel, <span style="color:#A020F0;">'PropertyChangeCallback'</span>, @callback_onPropertyChange<span style="color: #080;">&#41;</span>;</pre></div></div><p>The callback function receives two input arguments: The first is the <em>PropertyTableModel</em> object that fired the event, the second is a <em>PropertyChangeEvent</em> object with properties <b>PropertyName</b>, <b>OldValue</b> and <b>NewValue</b>. The <em>PropertyTableModel</em>&#8216;s <em>getProperty(PropertyName)</em> method may be used to fetch the <em>Property</em> instance that has changed.</p><p>Callbacks enable property value validation: <b>OldValue</b> can be used to restore the original property value, if <b>NewValue</b> fails to meet some criteria that cannot be programmed into the cell editor. We may, for instance, set the property type to a string; then, in our callback function, use <i><b>str2num</b></i> as a validator to try to convert <b>NewValue</b> to a numeric matrix. If the conversion fails, we restore the <b>OldValue</b>:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> callback_onPropertyChange<span style="color: #080;">&#40;</span>model, event<span style="color: #080;">&#41;</span>
   string = event.<span style="">getNewValue</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
   <span style="color: #080;">&#91;</span>value, isvalid<span style="color: #080;">&#93;</span> = <span style="color: #0000FF;">str2num</span><span style="color: #080;">&#40;</span>string<span style="color: #080;">&#41;</span>; <span style="color: #228B22;">%#ok</span>
   prop = model.<span style="">getProperty</span><span style="color: #080;">&#40;</span>event.<span style="">getPropertyName</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
   <span style="color: #0000FF;">if</span> isvalid  <span style="color: #228B22;">% standardize value entered</span>
      string = <span style="color: #0000FF;">mat2str</span><span style="color: #080;">&#40;</span>value<span style="color: #080;">&#41;</span>;
   <span style="color: #0000FF;">else</span>  <span style="color: #228B22;">% restore previous value</span>
      string = event.<span style="">getOldValue</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;
   <span style="color: #0000FF;">end</span>
   prop.<span style="">setValue</span><span style="color: #080;">&#40;</span>string<span style="color: #080;">&#41;</span>;
   model.<span style="color: #0000FF;">refresh</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;  <span style="color: #228B22;">% refresh value onscreen</span></pre></div></div><p>The JIDE packages that are pre-bundled in Matlab contain numerous other useful classes. Some of these will be described in future articles.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/jide-property-grids/' rel='bookmark' title='JIDE Property Grids'>JIDE Property Grids</a> <small>The JIDE components pre-bundled in Matlab enable creating user-customized property grid tables...</small></li><li><a
href='http://undocumentedmatlab.com/blog/plot-linesmoothing-property/' rel='bookmark' title='Plot LineSmoothing property'>Plot LineSmoothing property</a> <small>LineSmoothing is a hidden and undocumented plot line property that creates anti-aliased (smooth unpixelized) lines in Matlab plots...</small></li><li><a
href='http://undocumentedmatlab.com/blog/axes-looseinset-property/' rel='bookmark' title='Axes LooseInset property'>Axes LooseInset property</a> <small>Matlab plot axes have an undocumented LooseInset property that sets empty margins around the axes, and can be set to provide a tighter fit of the axes to their surroundings....</small></li><li><a
href='http://undocumentedmatlab.com/blog/date-selection-components/' rel='bookmark' title='Date selection components'>Date selection components</a> <small>The JIDE package, pre-bundled in Matlab, contains several GUI controls for selecting dates - this article explains how they can be used...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/advanced-jide-property-grids/feed/</wfw:commentRss> <slash:comments>17</slash:comments> </item> <item><title>Matlab and the Event Dispatch Thread (EDT)</title><link>http://undocumentedmatlab.com/blog/matlab-and-the-event-dispatch-thread-edt/</link> <comments>http://undocumentedmatlab.com/blog/matlab-and-the-event-dispatch-thread-edt/#comments</comments> <pubDate>Wed, 10 Mar 2010 07:18:58 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <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[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.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/inactive-control-tooltips-event-chaining/' rel='bookmark' title='Inactive Control Tooltips &amp; Event Chaining'>Inactive Control Tooltips &#038; Event Chaining</a> <small>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....</small></li><li><a
href='http://undocumentedmatlab.com/blog/javacomponent/' rel='bookmark' title='The javacomponent function'>The javacomponent function</a> <small>Matlab's built-in javacomponent function can be used to display Java components in Matlab application - this article details its usages and limitations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-matlab-labels/' rel='bookmark' title='Customizing Matlab labels'>Customizing Matlab labels</a> <small>Matlab's text uicontrol is not very customizable, and does not support HTML or Tex formatting. This article shows how to display HTML labels in Matlab and some undocumented customizations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/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><pre> </pre>]]></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.</p><p>If we execute the code below we will probably see nothing until the loop completes and the figure appears with the text label showing &#8217;10000&#8242;:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">h = <span style="color: #0000FF;">figure</span>;
txt = <span style="color: #0000FF;">uicontrol</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Parent'</span>,h, <span style="color:#A020F0;">'Style'</span>,<span style="color:#A020F0;">'text'</span>, <span style="color:#A020F0;">'String'</span>,<span style="color:#A020F0;">'1'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">for</span> n = <span style="color: #33f;">1</span><span style="color: #F0F;">:</span><span style="color: #33f;">10000</span>
    <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>txt,<span style="color:#A020F0;">'String'</span>,<span style="color: #0000FF;">int2str</span><span style="color: #080;">&#40;</span>n<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">end</span> <span style="color: #228B22;">%for</span></pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">h = <span style="color: #0000FF;">figure</span>;
txt = <span style="color: #0000FF;">uicontrol</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Parent'</span>,h, <span style="color:#A020F0;">'Style'</span>,<span style="color:#A020F0;">'text'</span>, <span style="color:#A020F0;">'String'</span>,<span style="color:#A020F0;">'1'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">drawnow</span>;
<span style="color: #0000FF;">for</span> n = <span style="color: #33f;">1</span><span style="color: #F0F;">:</span><span style="color: #33f;">10000</span>
    <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>txt,<span style="color:#A020F0;">'String'</span>,<span style="color: #0000FF;">int2str</span><span style="color: #080;">&#40;</span>n<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">drawnow</span>;
<span style="color: #0000FF;">end</span> <span style="color: #228B22;">%for</span></pre></div></div><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.</p><p>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.</p><p>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><div
class="wp_syntax"><div
class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">Runnable</span> runnable <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Runnable</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> run<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">//GUI Code here</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #003399;">EventQueue</span>.<span style="color: #006633;">invokeLater</span><span style="color: #009900;">&#40;</span>runnable<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div><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.</p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Create a button on the EDT</span>
btn = javaObjectEDT<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'javax.swing.JButton'</span><span style="color: #080;">&#41;</span>;
<span style="color: #228B22;">% this will run on EDT since btn was javaObjectEDT-created</span>
btn.<span style="">setText</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Button'</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Create a button NOT on the EDT</span>
btn2 = javax.<span style="">swing</span>.<span style="">JButton</span>;
<span style="color: #228B22;">% Dangerous! call will run on main Matlab thread</span>
btn2.<span style="">setText</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Button2'</span><span style="color: #080;">&#41;</span>;
<span style="color: #228B22;">% modify btn2 so its methods will start running on the EDT</span>
javaObjectEDT<span style="color: #080;">&#40;</span>btn2<span style="color: #080;">&#41;</span>;
btn2.<span style="">setText</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Button2'</span><span style="color: #080;">&#41;</span>;</pre></div></div><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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> tableExample
hFig = <span style="color: #0000FF;">figure</span>;
<span style="color: #0000FF;">drawnow</span>; <span style="color: #228B22;">%need to get figure rendered</span>
&nbsp;
<span style="color: #228B22;">%use Yair's createTable to add a javax.swing.JTable</span>
<span style="color: #228B22;">%http://www.mathworks.com/matlabcentral/fileexchange/14225-java-based-data-table</span>
<span style="color: #228B22;">%wrap ceateTable in javaObjectEDT to put the ensuing method calls on the EDT</span>
f = java.<span style="">awt</span>.<span style="">Font</span><span style="color: #080;">&#40;</span>java.<span style="">lang</span>.<span style="">String</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Dialog'</span><span style="color: #080;">&#41;</span>,java.<span style="">awt</span>.<span style="">Font</span>.<span style="">PLAIN</span>,<span style="color: #33f;">14</span><span style="color: #080;">&#41;</span>;
headers = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'Selected'</span>,<span style="color:#A020F0;">'File'</span>,<span style="color:#A020F0;">'Analysis Routine'</span>,<span style="color:#A020F0;">'Task Status'</span><span style="color: #080;">&#125;</span>;
tbl = javaObjectEDT<span style="color: #080;">&#40;</span>createTable<span style="color: #080;">&#40;</span>hFig,headers,<span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>,<span style="color: #0000FF;">false</span>,<span style="color:#A020F0;">'Font'</span>,f<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">%set column 1 to use check boxes and set up a change callback</span>
tbl.<span style="">setCheckBoxEditor</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
jtable = javaObjectEDT<span style="color: #080;">&#40;</span>tbl.<span style="">getTable</span><span style="color: #080;">&#41;</span>; <span style="color: #228B22;">%get the underlying Java Table. IMPORTANT: we need to put jtable on the EDT</span>
columnModel = javaObjectEDT<span style="color: #080;">&#40;</span>jtable.<span style="">getColumnModel</span><span style="color: #080;">&#41;</span>; <span style="color: #228B22;">%now we can now do direct calls safely on jtable</span>
selectColumn = javaObjectEDT<span style="color: #080;">&#40;</span>columnModel.<span style="">getColumn</span><span style="color: #080;">&#40;</span><span style="color: #33f;">0</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
selectColumnCellEditor = selectColumn.<span style="">getCellEditor</span>;
chk = javaMethodEDT<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'getComponent'</span>,selectColumnCellEditor<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>chk,<span style="color:#A020F0;">'ItemStateChangedCallback'</span>,@chkChange_Callback<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">%make column three a combo drop down</span>
analysisTable = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'Analysis1'</span>;<span style="color:#A020F0;">'Analysis2'</span>;<span style="color:#A020F0;">'Analysis3'</span><span style="color: #080;">&#125;</span>;
cb = javaObjectEDT<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'com.mathworks.mwswing.MJComboBox'</span>,analysisTable<span style="color: #080;">&#41;</span>;
cb.<span style="">setEditable</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">false</span><span style="color: #080;">&#41;</span>;
cb.<span style="">setFont</span><span style="color: #080;">&#40;</span>f<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>cb,<span style="color:#A020F0;">'ItemStateChangedCallback'</span>,@cbChange_Callback<span style="color: #080;">&#41;</span>;
editor = javaObjectEDT<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'javax.swing.DefaultCellEditor'</span>,cb<span style="color: #080;">&#41;</span>;
analysisColumn = javaObjectEDT<span style="color: #080;">&#40;</span>columnModel.<span style="">getColumn</span><span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
analysisColumn.<span style="">setCellEditor</span><span style="color: #080;">&#40;</span>editor<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">%set some column with restrictions</span>
selectColumn.<span style="">setMaxWidth</span><span style="color: #080;">&#40;</span><span style="color: #33f;">100</span><span style="color: #080;">&#41;</span>;
analysisColumn.<span style="">setPreferredWidth</span><span style="color: #080;">&#40;</span><span style="color: #33f;">300</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">%set the data</span>
SELECTED = java.<span style="">awt</span>.<span style="">event</span>.<span style="">ItemEvent</span>.<span style="">SELECTED</span>;
tbl.<span style="">setData</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#123;</span><span style="color: #0000FF;">false</span>,<span style="color:#A020F0;">'file1'</span>,<span style="color:#A020F0;">'Analysis2'</span>,<span style="color:#A020F0;">'Analysis2'</span>;<span style="color: #F0F;">...</span>
             <span style="color: #0000FF;">true</span>,<span style="color:#A020F0;">'file2'</span>,<span style="color:#A020F0;">'Analysis3'</span>,<span style="color:#A020F0;">'Analysis3'</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">drawnow</span>;
&nbsp;
    <span style="color: #0000FF;">function</span> cbChange_Callback<span style="color: #080;">&#40;</span>src,ev<span style="color: #080;">&#41;</span> <span style="color: #228B22;">%#ok</span>
        jRow = jtable.<span style="">getSelectedRow</span>;
        stateChange = javaMethodEDT<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'getStateChange'</span>,ev<span style="color: #080;">&#41;</span>;
        <span style="color: #0000FF;">if</span> stateChange == SELECTED
            newData = javaMethodEDT<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'getItem'</span>,ev<span style="color: #080;">&#41;</span>;
            model = jtable.<span style="">getModel</span>;
            javaMethodEDT<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'setValueAt'</span>,model,newData,jRow,<span style="color: #33f;">3</span><span style="color: #080;">&#41;</span>;
        <span style="color: #0000FF;">end</span> <span style="color: #228B22;">%if</span>
    <span style="color: #0000FF;">end</span> <span style="color: #228B22;">%cbChange</span>
&nbsp;
    <span style="color: #0000FF;">function</span> chkChange_Callback<span style="color: #080;">&#40;</span>src,ev<span style="color: #080;">&#41;</span> <span style="color: #228B22;">%#ok</span>
        chkBox = javaMethodEDT<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'getItem'</span>,ev<span style="color: #080;">&#41;</span>;
        <span style="color: #0000FF;">if</span> <span style="color: #0000FF;">logical</span><span style="color: #080;">&#40;</span>javaMethodEDT<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'isSelected'</span>,chkBox<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
            beep; <span style="color: #228B22;">%put useful code here</span>
        <span style="color: #0000FF;">else</span>
            beep;
            <span style="color: #0000FF;">pause</span><span style="color: #080;">&#40;</span><span style="color: #33f;">0.1</span><span style="color: #080;">&#41;</span>
            beep; <span style="color: #228B22;">%put useful code here</span>
        <span style="color: #0000FF;">end</span> <span style="color: #228B22;">%if</span>
    <span style="color: #0000FF;">end</span> <span style="color: #228B22;">%chkChange_Callback</span>
&nbsp;
<span style="color: #0000FF;">end</span> <span style="color: #228B22;">%tableExample</span></pre></div></div><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.</p><p><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)</p><p>For this reason, I am using the following method in my projects:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> result = javaObjEDT<span style="color: #080;">&#40;</span><span style="color: #0000FF;">varargin</span><span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%Placeholder of Matlab's buggy javaObjectEDT function on R2008a</span>
&nbsp;
<span style="color: #228B22;">% Programmed by Yair M. Altman: altmany(at)gmail.com</span>
<span style="color: #228B22;">% $Revision: 1.2 $  $Date: 2009/01/25 11:31:08 $</span>
&nbsp;
  <span style="color: #0000FF;">try</span>
      <span style="color: #0000FF;">try</span>
          result = <span style="color: #0000FF;">varargin</span><span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span>;
      <span style="color: #0000FF;">catch</span>
          result = <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>;
      <span style="color: #0000FF;">end</span>
      v = <span style="color: #0000FF;">version</span>;
      <span style="color: #0000FF;">if</span> <span style="color: #0000FF;">str2double</span><span style="color: #080;">&#40;</span>v<span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #F0F;">:</span><span style="color: #33f;">3</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> &gt; <span style="color: #33f;">7.6</span>
          result = <span style="color: #0000FF;">builtin</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'javaObjectEDT'</span>,<span style="color: #0000FF;">varargin</span><span style="color: #080;">&#123;</span><span style="color: #F0F;">:</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
      <span style="color: #0000FF;">end</span>
  <span style="color: #0000FF;">catch</span>
      <span style="color: #228B22;">% never mind</span>
  <span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">end</span></pre></div></div><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.</p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">btn = awtcreate<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'javax.swing.JButton'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">awtinvoke</span><span style="color: #080;">&#40;</span>btn,<span style="color:#A020F0;">'setText(Ljava/lang/String;)'</span>,<span style="color:#A020F0;">'click me'</span><span style="color: #080;">&#41;</span></pre></div></div><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.</p><p>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.</p><p>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.</p><p>A very rare <a
target="_blank" rel="nofollow" href="http://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.</p><p>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><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">%CALLBACKONEDTQUEUE will place a callback on the EDT to asynchronously</span>
<span style="color: #228B22;">%run a function.</span>
<span style="color: #228B22;">%CALLBBACKONEDTQUEUE(FCN) will run function handle FCN once all previous</span>
<span style="color: #228B22;">%methods dispatched to the EDT have completed.</span>
<span style="color: #228B22;">%CALLBBACKONEDTQUEUE(FCN,ARG1,ARG2,...) ill run function handle FCN with</span>
<span style="color: #228B22;">%arguments ARG1,ARG2...once all previous methods dispatched to the EDT</span>
<span style="color: #228B22;">%have completed.</span>
<span style="color: #228B22;">%Note that the function is still executing on the main Matlab thread. This</span>
<span style="color: #228B22;">%function just delays when it will be called.</span>
<span style="color: #0000FF;">function</span> callbackOnEDTQueue<span style="color: #080;">&#40;</span><span style="color: #0000FF;">varargin</span><span style="color: #080;">&#41;</span>
    validateattributes<span style="color: #080;">&#40;</span><span style="color: #0000FF;">varargin</span><span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span>,<span style="color: #080;">&#123;</span><span style="color:#A020F0;">'function_handle'</span><span style="color: #080;">&#125;</span>,<span style="color: #080;">&#123;</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
    callbackObj = handle<span style="color: #080;">&#40;</span>com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">Callback</span>,<span style="color:#A020F0;">'callbackProperties'</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>callbackObj,<span style="color:#A020F0;">'delayedCallback'</span>,<span style="color: #080;">&#123;</span>@cbEval,<span style="color: #0000FF;">varargin</span><span style="color: #080;">&#40;</span><span style="color: #F0F;">:</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
    callbackObj.<span style="">postCallback</span>;
&nbsp;
    <span style="color: #0000FF;">function</span> cbEval<span style="color: #080;">&#40;</span>src,evt,args<span style="color: #080;">&#41;</span> <span style="color: #228B22;">%#ok</span>
        <span style="color: #0000FF;">feval</span><span style="color: #080;">&#40;</span>args<span style="color: #080;">&#123;</span><span style="color: #F0F;">:</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">end</span> <span style="color: #228B22;">%cbEval</span>
<span style="color: #0000FF;">end</span> <span style="color: #228B22;">%callbackOnEDTQueue</span></pre></div></div><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/inactive-control-tooltips-event-chaining/' rel='bookmark' title='Inactive Control Tooltips &amp; Event Chaining'>Inactive Control Tooltips &#038; Event Chaining</a> <small>Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....</small></li><li><a
href='http://undocumentedmatlab.com/blog/javacomponent/' rel='bookmark' title='The javacomponent function'>The javacomponent function</a> <small>Matlab's built-in javacomponent function can be used to display Java components in Matlab application - this article details its usages and limitations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-matlab-labels/' rel='bookmark' title='Customizing Matlab labels'>Customizing Matlab labels</a> <small>Matlab's text uicontrol is not very customizable, and does not support HTML or Tex formatting. This article shows how to display HTML labels in Matlab and some undocumented customizations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/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></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/matlab-and-the-event-dispatch-thread-edt/feed/</wfw:commentRss> <slash:comments>21</slash:comments> </item> </channel> </rss>

<!-- W3 Total Cache: Minify debug info:
Engine:             disk: basic
Theme:              b7666
Template:           tag
-->
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Served from: undocumentedmatlab.com @ 2012-02-04 03:25:24 -->

<!-- W3 Total Cache: Page cache debug info:
Engine:             disk: enhanced
Cache key:          blog/tag/callbacks/feed/_index.xml_gzip
Caching:            enabled
Status:             not cached
Creation Time:      2.469s
Header info:
X-Pingback:         http://undocumentedmatlab.com/blog/xmlrpc.php
Set-Cookie:         wpgb_visit_last_php-default=1328351122; expires=Sun, 03-Feb-2013 10:25:22 GMT; path=/
Content-Type:       text/xml; charset=UTF-8
Last-Modified:      Sat, 04 Feb 2012 10:25:24 GMT
Vary:               Accept-Encoding, Cookie
Expires:            Sat, 04 Feb 2012 11:25:24 GMT
Pragma:             public
Cache-Control:      public, must-revalidate, proxy-revalidate
Etag:               d9ab2cabe5e734b38d95807c4eb1f8f0
Content-Encoding:   gzip
-->
