<?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>uicontrol &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/uicontrol/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Fri, 04 Aug 2017 09:37:52 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
	<item>
		<title>Matlab GUI training seminars &#8211; Zurich, 29-30 August 2017</title>
		<link>https://undocumentedmatlab.com/articles/matlab-gui-training-seminars-zurich-29-30-august-2017?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-gui-training-seminars-zurich-29-30-august-2017</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-gui-training-seminars-zurich-29-30-august-2017#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Fri, 04 Aug 2017 09:37:52 +0000</pubDate>
				<category><![CDATA[Public presentation]]></category>
		<category><![CDATA[AppDesigner]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[GUIDE]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JIDE]]></category>
		<category><![CDATA[training]]></category>
		<category><![CDATA[uicontrol]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6992</guid>

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

					<description><![CDATA[<p>HTML can be used to add image icons to Matlab listbox and popup (drop-down) controls. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/icon-images-in-matlab-uicontrols">Icon images &amp; text in Matlab uicontrols</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/images-in-matlab-uicontrols-and-labels" rel="bookmark" title="Images in Matlab uicontrols &amp; labels">Images in Matlab uicontrols &amp; labels </a> <small>Images can be added to Matlab controls and labels in a variety of manners, documented and undocumented. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/animated-busy-spinning-icon" rel="bookmark" title="Animated busy (spinning) icon">Animated busy (spinning) icon </a> <small>An animated spinning icon label can easily be embedded in Matlab GUI. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uitab-colors-icons-images" rel="bookmark" title="Uitab colors, icons and images">Uitab colors, icons and images </a> <small>Matlab's semi-documented tab panels can be customized using some undocumented hacks...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/panel-level-uicontrols" rel="bookmark" title="Panel-level uicontrols">Panel-level uicontrols </a> <small>Matlab's uipanel contains a hidden handle to the title label, which can be modified into a checkbox or radio-button control...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>One of my consulting clients recently asked me if I knew any builtin Matlab GUI control that could display a list of <a href="http://www.mathworks.com/help/matlab/ref/colormap.html#inputarg_name" rel="nofollow" target="_blank">colormap names</a> alongside their respective image icons, in a listbox or popup menu (drop-down/combo-box):<br />
<center><figure style="width: 520px" class="wp-caption aligncenter"><img decoding="async" alt="Matlab listbox with icon images" src="https://undocumentedmatlab.com/images/html_listbox.png" title="Matlab listbox with icon images" width="270" height="200" /> &nbsp; <img loading="lazy" decoding="async" alt="Matlab popup menu (dropdown/combobox) with icon images" src="https://undocumentedmatlab.com/images/html_popup.png" title="Matlab popup menu (dropdown/combobox) with icon images" width="224" height="264" /><figcaption class="wp-caption-text">Matlab listbox (left) & popup menu (right) with icon images</figcaption></figure></center><br />
My initial thought was that this should surely be possible, since <b>Colormap</b> is a documented figure property, that should therefore be listed inside the <a href="http://www.mathworks.com/help/matlab/ref/inspect.html" rel="nofollow" target="_blank">inspector window</a>, and should therefore have an associated builtin Java control for the dropdown (just like other inspector controls, which are part of the <code>com.mathworks.mlwidgets</code> package, or possibly as a standalone control in the <code>com.mathworks.mwswing</code> package). To my surprise it turns out that for some unknown reason MathWorks neglected to add the <b>Colormap</b> property (and associated Java controls) to the inspector. This property is fully documented and all, just like <b>Color</b> and other standard figure properties, but unlike them <b>Colormap</b> can only be modified programmatically, not via the inspector window. Matlab does provide the related <i><b>colormapeditor</b></i> function and associated dialog window, but I would have expected a simple drop-down of the standard builtin colormaps to be available in the inspector. Anyway, this turned out to be a dead-end.<br />
It turns out that we can relatively easily implement the requested listbox/combo-box using a bit of HTML magic, <a href="/articles/aligning-uicontrol-contents" target="_blank">as I explained</a> last week. The basic idea is for each of the listbox/combobox items to be an HTML string that contains both an &lt;img&gt; tag for the icon and the item label text. For example, such a string might contain something like this (parula is Matlab&#8217;s default colormap in HG2, starting in R2014b):</p>
<pre lang="xml"><html><img decoding="async" src="http://www.mathworks.com/help/matlab/ref/colormap_parula.png">parula</pre>
<p><center><figure style="width: 434px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="parula colormap image" src="http://www.mathworks.com/help/matlab/ref/colormap_parula.png" title="parula colormap image" width="434" height="27" /><figcaption class="wp-caption-text">parula colormap image</figcaption></figure></center><br />
<span id="more-6687"></span>Of course, it would be a bit inefficient for each of the icons to be fetched from the internet. Luckily, the full set of Matlab documentation is typically installed on the local computer as part of the standard Matlab installation, beneath the <i><b>docroot</b></i> folder (e.g., <i>C:\Program Files\Matlab\R2016b\help</i>). In our specific case, the parula colormap image is located in:</p>
<pre lang="matlab">imageFilename = [docroot, '/matlab/ref/colormap_parula.png']</pre>
<p>Note that for a local image to be accepted by HTML, it needs to follow certain conventions. In our case, the HTML string for displaying the above image is:</p>
<pre lang="xml"><html><img decoding="async" src="file:///C:/Program%20Files/Matlab/R2016b/help/matlab/ref/colormap_parula.png">parula</pre>
<blockquote><p><u>Warning</u>: it&#8217;s easy when dealing with HTML images in Matlab to get the format confused, resulting in a red-x icon. I <a href="/articles/images-in-matlab-uicontrols-and-labels" target="_blank">discussed this issue</a> some 4 years ago, which is still relevant.</p></blockquote>
<p>How can we get the list of available builtin colormaps? The standard Matlab way of doing this would be something like this:</p>
<pre lang="matlab">
>> possibleColormaps = set(gcf,'Colormap')
possibleColormaps =
     {}
</pre>
<p>but as we can see, for some unknown reason (probably another MathWorks omission), Matlab does not list the names of its available builtin colormaps.<br />
Fortunately, all the builtin colormaps have image filenames that follow the same convention, which make it easy to get this list by simply listing the names of the relevant files, from which we can easily create the necessary HTML strings:</p>
<pre lang="matlab">
>> iconFiles = dir([docroot, '/matlab/ref/colormap_*.png']);
>> colormapNames = regexprep({iconFiles.name}, '.*_(.*).png', '$1')
colormapNames =
  Columns 1 through 9
    'autumn'    'bone'    'colorcube'    'cool'    'copper'    'flag'    'gray'    'hot'    'hsv'
  Columns 10 through 18
    'jet'    'lines'    'parula'    'pink'    'prism'    'spring'    'summer'    'white'    'winter'
>> htmlStrings = strcat('<html><img decoding="async" width=200 height=10 src="file:///C:/Program%20Files/Matlab/R2016a/help/matlab/ref/colormap_', colormapNames', '.png">', colormapNames')
str =
    '<html><img decoding="async" width=200 height=10 src="file:///C:/Program%20Files/Matlab/R2016a/help/matlab/ref/colormap_autumn.png">autumn'
    '<html><img decoding="async" width=200 height=10 src="file:///C:/Program%20Files/Matlab/R2016a/help/matlab/ref/colormap_bone.png">bone'
    '<html><img decoding="async" width=200 height=10 src="file:///C:/Program%20Files/Matlab/R2016a/help/matlab/ref/colormap_colorcube.png">colorcube'
    ...
>> hListbox = uicontrol(gcf, 'Style','listbox', 'Units','pixel', 'Pos',[10,10,270,200], 'String',htmlStrings);
>> hPopup   = uicontrol(gcf, 'Style','popup',   'Units','pixel', 'Pos',[10,500,270,20], 'String',htmlStrings);
</pre>
<p>&#8230;which results in the screenshots at the top of this post.<br />
Note how I scaled the images to 10px high (so that the labels would be shown and not cropped vertically) and 200px wide (so that it becomes narrower than the default 434px). There&#8217;s really no need in this case for the full 434&#215;27 image size &#8211; such flat images scale very nicely, even when their aspect ratio is not preserved. You can adjust the <code>height</code> and <code>width</code> values for a best fit with you GUI.<br />
Unfortunately, it seems that HTML strings are not supported in the new web-based uifigure controls. This is not really Matlab&#8217;s fault because the way to customize labels in HTML controls is via CSS: directly embedding HTML code in labels does not work (it&#8217;s a Java-Swing feature, not a browser feature). I really hope that either HTML or CSS processing will be enabled for web-based uicontrol in a future Matlab release, because until that time uifigure uicontrols will remain seriously deficient compared to standard figure uicontrols. Until then, if we must use uifigures and wish to customize our labels or listbox items, we can directly access the underlying web controls, <a href="/articles/customizing-uifigures-part-2" rel="nofollow" target="_blank">as Iliya explained here</a>.<br />
<span id="rant"></span><br />
A blog reader <a href="/articles/using-pure-java-gui-in-deployed-matlab-apps#comment-389045" target="_blank">recently complained</a> that I&#8217;m abusing Swing and basically making Matlab work in unnatural ways, &#8220;<i>something it was never meant to be</i>&#8220;. I feel that using HTML as I&#8217;ve shown last week and in this post would fall under the same category in his eyes. To him and to others who complain I say that I have absolutely no remorse about doing this. When I purchase anything I have the full rights (within the scope of the license) to adapt it in whatever way fits my needs. As a software developer and manager for over 25 years, I&#8217;ve developed in dozens of programming languages and environments, and I still enjoy [ab]using Matlab. Matlab is a great environment to get things done quickly and if this sometimes requires a bit of HTML or Java hacks that make some people cringe, then that&#8217;s their problem, not mine &#8211; I&#8217;m content with being able to do in Matlab [nearly] everything I want, quickly, and move on to the next project. As long as it gets the job done, that&#8217;s fine by me. If this makes me more of an engineer than a computer scientist, then so be it.<br />
On the flip side, I say to those who claim that Matlab is lacking in this or that aspect, that in most likelihood the limitation is only in their minds, not in Matlab &#8211; we can do amazing stuff with Matlab if we just open our minds, and possibly use some undocumented hacks. I&#8217;m not saying that Matlab has no limitations, I&#8217;m just saying that in most cases they can be overcome if we took the time and trouble to look for a solution. Matlab is a great tool and yet many people are not aware of its potential. Blaming Matlab for its failings is just an easy excuse in many cases. Of course, MathWorks could help my crusade on this subject by enabling useful features such as easy GUI component customizations&#8230;<br />
On this sad day, I wish you all <i>Shanah Tova!</i></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/icon-images-in-matlab-uicontrols">Icon images &amp; text in Matlab uicontrols</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/images-in-matlab-uicontrols-and-labels" rel="bookmark" title="Images in Matlab uicontrols &amp; labels">Images in Matlab uicontrols &amp; labels </a> <small>Images can be added to Matlab controls and labels in a variety of manners, documented and undocumented. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/animated-busy-spinning-icon" rel="bookmark" title="Animated busy (spinning) icon">Animated busy (spinning) icon </a> <small>An animated spinning icon label can easily be embedded in Matlab GUI. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uitab-colors-icons-images" rel="bookmark" title="Uitab colors, icons and images">Uitab colors, icons and images </a> <small>Matlab's semi-documented tab panels can be customized using some undocumented hacks...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/panel-level-uicontrols" rel="bookmark" title="Panel-level uicontrols">Panel-level uicontrols </a> <small>Matlab's uipanel contains a hidden handle to the title label, which can be modified into a checkbox or radio-button control...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/icon-images-in-matlab-uicontrols/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Aligning uicontrol contents</title>
		<link>https://undocumentedmatlab.com/articles/aligning-uicontrol-contents?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=aligning-uicontrol-contents</link>
					<comments>https://undocumentedmatlab.com/articles/aligning-uicontrol-contents#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 22 Sep 2016 13:10:18 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[uicontrol]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6663</guid>

					<description><![CDATA[<p>Matlab uicontrols can often be customized using plain HTML/CSS, without need for advanced Java. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/aligning-uicontrol-contents">Aligning uicontrol contents</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/rich-contents-log-panel" rel="bookmark" title="Rich-contents log panel">Rich-contents log panel </a> <small>Matlab listboxes and editboxes can be used to display rich-contents HTML-formatted strings, which is ideal for log panels. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/spicing-up-matlab-uicontrol-tooltips" rel="bookmark" title="Spicing up Matlab uicontrol tooltips">Spicing up Matlab uicontrol tooltips </a> <small>Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/additional-uicontrol-tooltip-hacks" rel="bookmark" title="Additional uicontrol tooltip hacks">Additional uicontrol tooltip hacks </a> <small>Matlab's uicontrol tooltips have several limitations that can be overcome using the control's underlying Java object....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-line-position-in-edit-box-uicontrol" rel="bookmark" title="Setting line position in an edit-box uicontrol">Setting line position in an edit-box uicontrol </a> <small>Matlab uicontrols have many useful features that are only available via Java. Here's how to access them....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab automatically aligns the text contents of uicontrols: button labels are centered, listbox contents are left-aligned, and table cells align depending on their contents (left-aligned for strings, centered for logical values, and right-aligned for numbers). Unfortunately, the control&#8217;s <b>HorizontalAlignment</b> property is generally ignored by uicontrols. So how can we force Matlab buttons (for example) to have right-aligned labels, or for listbox/table cells to be centered? Undocumented Matlab has the answer, yet again&#8230;<br />
It turns out that there are at least two distinct ways to set uicontrol alignment, using HTML and <a href="/articles/button-customization" rel="nofollow" target="_blank">using Java</a>. Today I will only discuss the HTML variant.<br />
The HTML method relies on the fact that <a href="/articles/html-support-in-matlab-uicomponents" target="_blank">Matlab uicontrols accept and process HTML strings</a>. This was true ever since Matlab GUI started relying on Java Swing components (which inherently <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/html.html" rel="nofollow" target="_blank">accept HTML labels</a>) over a decade ago. This is expected to remain true even in Matlab&#8217;s upcoming <a href="/articles/customizing-uifigures-part-1" rel="nofollow" target="_blank">web-based GUI system</a>, since Matlab would need to consciously disable HTML in its web components, and I see no reason for MathWorks to do so. In short, HTML parsing of GUI control strings is here to stay for the foreseeable future.</p>
<pre lang="matlab">
% note: no need to close HTML tags, e.g. </font></html>
uicontrol('Style','list', 'Position',[10,10,70,70], 'String', ...
          {'<html><font color="red">Hello</font></html>', 'world', ...
           '<html><font style="font-family:impact;color:green"><i>What a', ...
           '<html><font color="blue" face="Comic Sans MS">nice day!'});
</pre>
<p><center><figure style="width: 80px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Listbox with HTML items" src="https://undocumentedmatlab.com/blog/wp-content/uploads/2009/03/html11.png" title="Listbox with HTML items" width="80" height="80" /><figcaption class="wp-caption-text">Listbox with HTML items</figcaption></figure></center><br />
While HTML formatting is generally frowned-upon compared to the alternatives, it provides a very quick and easy way to format text labels in various different manners, including using a combination of font faces, sizes, colors and other aspects (bold, italic, super/sub-script, underline etc.) within a single text label. This is naturally impossible to do with Matlab&#8217;s standard properties, but is super-easy with HTML placed in the label&#8217;s <b>String</b> property.<br />
<span id="more-6663"></span><br />
Unfortunately, while Java Swing (and therefore Matlab) honors only a [large] sub-set of HTML and CSS. The most important directives are parsed but <a href="http://stackoverflow.com/questions/7311235/java-html-css-in-swing-display-inline-not-working" rel="nofollow" target="_blank">some others are not</a>, and this is often difficult to debug. Luckily, using HTML and CSS there are often multiple ways to achieve the same visual effect, so if one method fails we can usually find an alternative. Such was the case when a reader <a href="/articles/html-support-in-matlab-uicomponents#comment-386047" rel="nofollow" target="_blank">asked me</a> why the following seemingly-simple HTML snippet failed to right-align his button label:</p>
<pre lang="matlab">
hButton.String = '<html><div style="text-align:right">text';
</pre>
<p>As I explained in my answer, it&#8217;s not Matlab that ignores the CSS <code>align</code> directive but rather the underlying Swing behavior, which snugly fits the text in the center of the button, and of course aligning text within a tight-fitting box has no effect. The workaround that I suggested simply forces Swing to use a non-tightly-fitting boundary box, within which we can indeed align the text:</p>
<pre lang="matlab">
pxPos = getpixelposition(hButton);
hButton.String = ['<html><div width="' num2str(pxPos(3)-20) 'px" align="right">text'];  % button margins use 20px
</pre>
<p><center><figure style="width: 140px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="centered (default) button label" src="https://undocumentedmatlab.com/images/button-center-align.gif" title="centered (default) button label" width="60" height="20" /> &nbsp; <img loading="lazy" decoding="async" alt="right-aligned button label" src="https://undocumentedmatlab.com/images/button-right-align.gif" title="right-aligned button label" width="60" height="20" /><figcaption class="wp-caption-text">Centered (default) and right-aligned button labels</figcaption></figure></center><br />
This solution is very easy to set up and maintain, and requires no special knowledge other than a bit of HTML/CSS, which most programmers know in this day and age.<br />
Of course, the solution relies on the actual button size. So, if the button is created with normalized units and changes its size when its parent container is resized, we&#8217;d need to set a callback function on the parent (e.g., <b>SizeChangedFcn</b> of a uipanel) to automatically adjust the button&#8217;s string based on its updated size. A better solution that would be independent of the button&#8217;s pixel-size and would work even when the button is resized needs to use Java.<br />
A related solution for table cells uses a different HTML-based trick: this time, we embed an HTML table cell within the Matlab control&#8217;s cell, employing the fact that HTML table cells can easily be aligned. We just need to ensure that the HTML cell is defined to be larger than the actual cell width, so that the alignment fits well. We do this by setting the HTML cell width to 9999 pixels (note that the <code>tr</code> and <code>td</code> HTML tags are necessary, but the <code>table</code> tag is optional):</p>
<pre lang="matlab">
uitable('Units','norm','Pos',[0,0,0.3,0.3], 'Data', ...
        {'Left', ...
         '<html><tr><td align=center width=9999>Center', ...
         '<html><tr><td align=right  width=9999>Right'});
</pre>
<p><center><figure style="width: 200px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Non-default alignment of uitable cells" src="https://undocumentedmatlab.com/images/uitable-cell-align.gif" title="Non-default alignment of uitable cells" width="200" height="40" /><figcaption class="wp-caption-text">Non-default alignment of uitable cells</figcaption></figure></center><br />
As noted above, a better solution might be to set the underlying Java component&#8217;s alignment properties (or in the case of the uitable, its underlying <code>JTable</code> component&#8217;s cellrenderer&#8217;s alignment). But in the general case, simple HTML such as above could well be sufficient.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/aligning-uicontrol-contents">Aligning uicontrol contents</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/rich-contents-log-panel" rel="bookmark" title="Rich-contents log panel">Rich-contents log panel </a> <small>Matlab listboxes and editboxes can be used to display rich-contents HTML-formatted strings, which is ideal for log panels. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/spicing-up-matlab-uicontrol-tooltips" rel="bookmark" title="Spicing up Matlab uicontrol tooltips">Spicing up Matlab uicontrol tooltips </a> <small>Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/additional-uicontrol-tooltip-hacks" rel="bookmark" title="Additional uicontrol tooltip hacks">Additional uicontrol tooltip hacks </a> <small>Matlab's uicontrol tooltips have several limitations that can be overcome using the control's underlying Java object....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-line-position-in-edit-box-uicontrol" rel="bookmark" title="Setting line position in an edit-box uicontrol">Setting line position in an edit-box uicontrol </a> <small>Matlab uicontrols have many useful features that are only available via Java. Here's how to access them....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/aligning-uicontrol-contents/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Listbox selection hacks</title>
		<link>https://undocumentedmatlab.com/articles/listbox-selection-hacks?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=listbox-selection-hacks</link>
					<comments>https://undocumentedmatlab.com/articles/listbox-selection-hacks#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 13 Jul 2016 15:36:19 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[uicontrol]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6534</guid>

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

					<description><![CDATA[<p>Matlab listbox and multi-line editbox scrollbars can easily be made smarter, for improved appearance. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/smart-listbox-editbox-scrollbars">Smart listbox &amp; editbox scrollbars</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-editbox-scrollbars" rel="bookmark" title="Customizing listbox &amp; editbox scrollbars">Customizing listbox &amp; editbox scrollbars </a> <small>Matlab listbox and multi-line editbox uicontrols have pre-configured scrollbars. This article shows how they can be customized....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/editbox-data-input-validation" rel="bookmark" title="Editbox data input validation">Editbox data input validation </a> <small>Undocumented features of Matlab editbox uicontrols enable immediate user-input data validation...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/rich-matlab-editbox-contents" rel="bookmark" title="Rich Matlab editbox contents">Rich Matlab editbox contents </a> <small>The Matlab editbox uicontrol does not handle HTML contents as do other uicontrols. In this article I show how this limitation can be removed....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/listbox-selection-hacks" rel="bookmark" title="Listbox selection hacks">Listbox selection hacks </a> <small>Matlab listbox selection can be customized in a variety of undocumented ways. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A good friend recently asked me for examples where using Java in Matlab programs provides a significant benefit that would offset the risk of using undocumented/unsupported functionality, which may possibly stop working in some future Matlab release. Today I will discuss a very easy Java-based hack that in my opinion improves the appearance of Matlab GUIs with minimal risk of a catastrophic failure in a future release.<br />
The problem with Matlab listbox and multi-line editbox controls in the current (non web-based) GUI, is that they use a scrollbar whose <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html#scrollbars" rel="nofollow" target="_blank">behavior policy</a> is set to <a href="https://docs.oracle.com/javase/7/docs/api/javax/swing/ScrollPaneConstants.html#VERTICAL_SCROLLBAR_ALWAYS" rel="nofollow" target="_blank"><code>VERTICAL_SCROLLBAR_ALWAYS</code></a>. This causes the vertical scrollbar to appear even when the listbox does not really require it. In many cases, when the listbox is too narrow, this also causes the automatic appearance of a horizontal scrollbar. The end result is a listbox that displays 2 useless scrollbars, that possibly hide some listbox contents, and are a sore to the eyes:<br />
<center><figure style="width: 130px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Standard (left) and smart (right) listbox scrollbars" src="https://undocumentedmatlab.com/images/listbox_scrollbars.png" title="Standard (left) and smart (right) listbox scrollbars" width="130" height="85" /><figcaption class="wp-caption-text">Standard (left) and smart (right) listbox scrollbars</figcaption></figure> &nbsp;&nbsp;&nbsp; <figure style="width: 200px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="default scrollbars (VERTICAL_SCROLLBAR_ALWAYS)" src="https://undocumentedmatlab.com/images/editbox7a.png" title="default scrollbars (VERTICAL_SCROLLBAR_ALWAYS)" width="75" height="60" /><figcaption class="wp-caption-text">default scrollbars (VERTICAL_SCROLLBAR_ALWAYS)</figcaption></figure>  <figure style="width: 220px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="non-default scrollbars (VERTICAL_SCROLLBAR_AS_NEEDED)" src="https://undocumentedmatlab.com/images/editbox7b.png" title="non-default scrollbars (VERTICAL_SCROLLBAR_AS_NEEDED)" width="75" height="60" /> &nbsp;&nbsp;&nbsp; <img loading="lazy" decoding="async" alt="non-default scrollbars (VERTICAL_SCROLLBAR_AS_NEEDED)" src="https://undocumentedmatlab.com/images/editbox7c.png" title="non-default scrollbars (VERTICAL_SCROLLBAR_AS_NEEDED)" width="75" height="60" /><figcaption class="wp-caption-text">non-default scrollbars (VERTICAL_SCROLLBAR_AS_NEEDED)</figcaption></figure></center><br />
By default, Matlab implements a vertical scrollbar policy of <code>VERTICAL_SCROLLBAR_ALWAYS</code> for sufficiently tall uicontrols (>20-25 pixels, which practically means always) and <code>VERTICAL_SCROLLBAR_NEVER</code> for shorter uicontrols (this may possibly be platform-dependent).<br />
A similar problem happens with the horizontal scrollbar: Matlab implements a horizontal scrollbar policy of <code>HORIZONTAL_SCROLLBAR_NEVER</code> for all editboxes and also for narrow listboxes (<35 pixels), and <code>HORIZONTAL_SCROLLBAR_AS_NEEDED</code> for wide listboxes.<br />
In many cases we may wish to modify the settings, as in the example shown above. The solution to this is very easy, as I <a href="/articles/customizing-listbox-editbox-scrollbars" rel="nofollow" target="_blank">explained back in 2010</a>.<span id="more-6379"></span><br />
All we need to do is to retrieve the control&#8217;s underlying Java reference (a Java <a href="https://docs.oracle.com/javase/7/docs/api/javax/swing/JScrollPane.html" rel="nofollow" target="_blank"><code>JScrollPane</code></a> object) and change the policy value to <a href="https://docs.oracle.com/javase/7/docs/api/javax/swing/ScrollPaneConstants.html#VERTICAL_SCROLLBAR_AS_NEEDED" rel="nofollow" target="_blank"><code>VERTICAL_SCROLLBAR_AS_NEEDED</code></a>:</p>
<pre lang="matlab">
% Create a multi-line (Max>1) editbox uicontrol
hEditbox = uicontrol('style','edit', 'max',5, ...);
try  % graceful-degradation for future compatibility
   % Get the Java scroll-pane container reference
   jScrollPane = findjobj(hEditbox);
   % Modify the scroll-pane's scrollbar policies
   % (note the equivalent alternative methods used below)
   set(jScrollPane,'VerticalScrollBarPolicy',javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);   %VERTICAL_SCROLLBAR_AS_NEEDED=20
   jScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);  %HORIZONTAL_SCROLLBAR_AS_NEEDED=30
catch
   % Never mind...
end
</pre>
<p>Note that updating the uicontrol handle <b>Position</b> property has the side-effect of automatically reverting the scrollbar policies to their default values (<code>HORIZONTAL_SCROLLBAR_NEVER</code> and <code>VERTICAL_SCROLLBAR_ALWAYS/NEVER</code>). This also happens whenever the uicontrol is resized interactively (by resizing its container figure window, for example). It is therefore advisable to set jScrollPane&#8217;s <b>ComponentResizedCallback</b> property to &#8220;unrevert&#8221; the policies:</p>
<pre lang="matlab">
cbFunc = @(h,e) set(h,'VerticalScrollBarPolicy',20, 'HorizontalScrollBarPolicy',30);
hjScrollPane = handle(jScrollPane,'CallbackProperties');
set(hjScrollPane,'ComponentResizedCallback',cbFunc);
</pre>
<h3 id="smart_scrollbars"><i>smart_scrollbars</i> utility</h3>
<p>I created a new utility called <i><b>smart_scrollbars</b></i> that implements all of this, which you can <a href="http://www.mathworks.com/matlabcentral/fileexchange/56653-smart-scrollbars" rel="nofollow" target="_blank">download from the Matlab File Exchange</a>. The usage in Matlab code is very simple:</p>
<pre lang="matlab">
% Fix scrollbars for a specific listbox
hListbox = uicontrol('style','list', ...);
smart_scrollbars(hListbox)
% Fix scrollbars for a specific editbox
hEditbox = uicontrol('style','edit', 'max',5, ...);
smart_scrollbars(hEditbox)
% Fix all listbox/editbox scrollbars in a panel or figure
smart_scrollbars              % fixes all scrollbars in current figure (gcf)
smart_scrollbars(hFig)        % fixes all scrollbars in a specific figure
smart_scrollbars(hContainer)  % fixes all scrollbars in a container (panel/tab/...)
</pre>
<h3 id="performance">Performance considerations</h3>
<p>Finding the underlying <code>JScrollPane</code> reference of Matlab listboxes/editboxes can take some time. While the <a href="/articles/faster-findjobj" target="_blank">latest version of <i><b>findjobj</b></i></a> significantly improved the performance of this, it can still take quite a while in complex GUIs. For this reason, it is highly advisable to limit the search to a Java container of the control that includes as few internal components as possible.<br />
In R2014b or newer, this is easily achieved by wrapping the listbox/editbox control in a tightly-fitting invisible <i><b>uipanel</b></i>. The reason is that in R2014b, <i><b>uipanel</b></i>s have finally become full-fledged Java components (which they weren&#8217;t until then), but more to the point they now contain a property with a direct reference to the underlying <code>JPanel</code>. By using this panel reference we limit <i><b>findjobj</b></i>&#8216;s search only to the contained scrollpane, and this is much faster:</p>
<pre lang="matlab">
% Slower code:
hListbox = uicontrol('style','list', 'parent',hParent, 'pos',...);
smart_scrollbars(hListbox)
% Much faster (using a tightly-fitting transparent uipanel wrapper):
hPanel = uipanel('BorderType','none', 'parent',hParent, 'pos',...);  % same position/units/parent as above
hListbox = uicontrol('style','list', 'parent',hPanel, 'units','norm', 'pos',[0,0,1,1], ...);
smart_scrollbars(hListbox)
</pre>
<p>The <i><b>smart_scrollbars</b></i> utility detects cases where there is a potential for such speedups and reports it in a console warning message:</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; smart_scrollbars(hListbox)
<span style="color:#ED9E00;">Warning: smart_scrollbars can be much faster if the list/edit control is wrapped in a tightly-fitting uipanel (<span style="text-decoration:underline;">details</span>)</span></pre>
</div>
</div>
<p>If you wish, you can suppress this warning using code such as the following:</p>
<pre lang="matlab">
oldWarn = warning('off', 'YMA:smart_scrollbars:uipanel');
smart_scrollbars(hListbox)
warning(oldWarn);  % restore warnings
</pre>
<h3 id="compatibility">Musings on future compatibility</h3>
<p>Going back to my friend&#8217;s question at the top of today&#8217;s post, the risk of future compatibility was highlighted in the recent release of Matlab R2016a, which <a href="/articles/adding-a-search-box-to-figure-toolbar#uifigure" target="_blank">introduced</a> web-based <i><b>uifigures</b></i> and controls, for which the vast majority of Java hacks that I presented in this blog since 2009 (including today&#8217;s hack) will not work. While the full transition from Java-based to web-based GUIs is not expected anytime soon, this recent addition highlighted the risk inherent in using unsupported functionality.<br />
Users can take a case-by-case decision whether any improved functionality or appearance using Java hacks is worth the extra risk: On one hand, such hacks have been quite stable and worked remarkably well for the past decade, and will probably continue working into 2020 or so (or longer if you keep using a not up-to-the-moment Matlab release, or if you create compiled applications). On the other hand, once they stop working sometime in R2020a (or whenever), major code rewrites may possibly be required, depending on the amount of dependency of your code on these hacks.<br />
There is an obvious tradeoff between improved GUIs now and for the coming years, versus increased maintainability cost a few years in the future. Each specific GUI will have its own sweet spot on the wide spectrum between using no such hacks at all, through non-critical hacks that provide graceful functionality degradation if they ever fail, to major Java-based functionality that would require complete rework. It is certainly NOT an all-or-nothing decision. Users who take the conservative approach of using no unsupported feature at all, lose the opportunity to have professional grade Matlab GUIs today and in the upcoming years. Decisions, decisions, &#8230;<br />
In any case, we can reduce the risk of using such hacks today by carefully wrapping all their code in <i><b>try-catch</b></i> blocks. This way, even if the code fails in some future Matlab release, we&#8217;d still be left with a working implementation based on fully-supported functionality. This is the reason why I&#8217;ve used such a block in the code snippet above, as well as in my <i><b>smart_scrollbars</b></i> utility. What this means is that you can safely use <i><b>smart_scrollbars</b></i> in your code today and if the worst happens and it stops working in a few years, then it will simply do nothing without causing any error. In other word, future compatibility in the form of graceful degradation. I strongly advise using such defensive coding techniques whenever you use unsupported features. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/smart-listbox-editbox-scrollbars">Smart listbox &amp; editbox scrollbars</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-editbox-scrollbars" rel="bookmark" title="Customizing listbox &amp; editbox scrollbars">Customizing listbox &amp; editbox scrollbars </a> <small>Matlab listbox and multi-line editbox uicontrols have pre-configured scrollbars. This article shows how they can be customized....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/editbox-data-input-validation" rel="bookmark" title="Editbox data input validation">Editbox data input validation </a> <small>Undocumented features of Matlab editbox uicontrols enable immediate user-input data validation...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/rich-matlab-editbox-contents" rel="bookmark" title="Rich Matlab editbox contents">Rich Matlab editbox contents </a> <small>The Matlab editbox uicontrol does not handle HTML contents as do other uicontrols. In this article I show how this limitation can be removed....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/listbox-selection-hacks" rel="bookmark" title="Listbox selection hacks">Listbox selection hacks </a> <small>Matlab listbox selection can be customized in a variety of undocumented ways. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/smart-listbox-editbox-scrollbars/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Sliders in Matlab GUI</title>
		<link>https://undocumentedmatlab.com/articles/sliders-in-matlab-gui?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sliders-in-matlab-gui</link>
					<comments>https://undocumentedmatlab.com/articles/sliders-in-matlab-gui#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 10 Jun 2015 18:00:58 +0000</pubDate>
				<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[AppDesigner]]></category>
		<category><![CDATA[JIDE]]></category>
		<category><![CDATA[uicontrol]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5827</guid>

					<description><![CDATA[<p>Professional-looking slider controls can easily be integrated in Matlab GUI. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/sliders-in-matlab-gui">Sliders in Matlab GUI</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2" rel="bookmark" title="Sliders in Matlab GUI &#8211; part 2">Sliders in Matlab GUI &#8211; part 2 </a> <small>Matlab contains a variety of ways to define/display slider controls in GUI windows. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-spinners-in-matlab-gui" rel="bookmark" title="Using spinners in Matlab GUI">Using spinners in Matlab GUI </a> <small>Spinner controls can easily be added to Matlab GUI. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/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>
</div>
]]></description>
										<content:encoded><![CDATA[<p>One of my consulting clients asked me last week if I knew an easy way to integrate a range (dual-knob) slider control in Matlab GUI. Today&#8217;s post is an expansion of the answer I provided him, which I though might interest other Matlab users.</p>
<ul>
<li><a href="/articles/sliders-in-matlab-gui#Matlab">Matlab vs. Java sliders</a></li>
<li><a href="/articles/sliders-in-matlab-gui#JSlider">Using JSlider</a></li>
<li><a href="/articles/sliders-in-matlab-gui#range">Range (dual-knob) sliders</a></li>
<li><a href="/articles/sliders-in-matlab-gui#AppDesigner">AppDesigner &#8211; Matlab&#8217;s new GUI</a></li>
<li><a href="/articles/sliders-in-matlab-gui#conclusions">Conclusions and some personal musings</a></li>
</ul>
<h3 id="Matlab">Matlab vs. Java sliders</h3>
<p>As funny as it may sound, Matlab&#8217;s so-called &#8220;slider&#8221; control (<code>uicontrol('Style','slider')</code>) is actually implemented as a scroll-bar, rather than the more natural <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/slider.html">JSlider</a>. I believe that this is due to a design decision that occurred sometime in the 1990&#8217;s (sliders were not as prevalent then as they are nowadays). This was never corrected, probably for backward-compatibility reasons. So to this day, Matlab&#8217;s so-called &#8220;slider&#8221; is actually a scroll-bar, and we do not [yet] have a real slider control in standard Matlab, apparently since the &#8216;slider&#8217; <i><b>uicontrol</b></i> style is already in use. Spoiler alert: this <i>will</i> change soon &#8212; keep reading.<br />
It gets worse: for some reason Matlab&#8217;s implementation of the so-called &#8220;slider&#8221; uses a Windows95 look-and-feel that makes the control look antique in today&#8217;s GUI standards. Using Java Swing&#8217;s standard <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/7/docs/api/javax/swing/JScrollBar.html">JScrollBar</a> control would at least have made it appear more consistent with the other Matlab controls, which are all based more closely on Java Swing:<br />
<figure style="width: 210px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt='Matlab "slider" uicontrol (bottom), Java JScrollBar (above), and JSlider (top 2)' src="https://undocumentedmatlab.com/images/slider_vs_scrollbars.gif" title='Matlab "slider" uicontrol (bottom), Java JScrollBar (above), and JSlider (top 2)' width="210" height="145" /><figcaption class="wp-caption-text">Matlab "slider" <i><b>uicontrol</b></i> (bottom), <br />Java <code>JScrollBar</code> (above), <br />and <code>JSlider</code> (top 2)</figcaption></figure></p>
<pre lang='matlab'>
% Standard Matlab "slider"
uicontrol('style','slider', 'position',[10,10,200,20]);
% Standard Java JScrollBar
jScrollbar = javax.swing.JScrollBar;
jScrollbar.setOrientation(jScrollbar.HORIZONTAL);
javacomponent(jScrollbar,[10,40,200,20]);
% Standard Java JSlider (20px high if no ticks/labels, otherwise use 45px)
jSlider = javax.swing.JSlider;
javacomponent(jSlider,[10,70,200,45]);
</pre>
<p>I advise users of the current Matlab GUI to use <code>JScrollBar</code> or <code>JSlider</code>, rather than Matlab&#8217;s standard &#8220;slider&#8221; <i><b>uicontrol</b></i>. The rest of today&#8217;s post will discuss the <code>JSlider</code> variant.<br />
<span id="more-5827"></span></p>
<h3 id="JSlider">Using JSlider</h3>
<p>As shown above, we can use the <i><b><a target="_blank" href="/articles/javacomponent">javacomponent</a></b></i> function to display any Java component in a Matlab container (such as <i><b>uipanel</b></i> or figure). We can easily modify the slider&#8217;s appearance using its internal properties:</p>
<pre lang='matlab'>set(jSlider, 'Value',84, 'MajorTickSpacing',20, 'PaintLabels',true);  % with labels, no ticks</pre>
<p><center><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/003x016.png" title="JSlider customization" alt="JSlider customization" width="130" height="40" /></center></p>
<pre lang='matlab'>set(jSlider, 'Value',22, 'PaintLabels',false, 'PaintTicks',true);  % with ticks, no labels</pre>
<p><center><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/003x017.png" title="JSlider customization" alt="JSlider customization" width="130" height="40" /></center></p>
<pre lang='matlab'>jSlider.setPaintLabels(true);  % or: jSlider.setPaintLabels(1);  % with both ticks and labels</pre>
<p><center><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/003x018.png" title="JSlider customization" alt="JSlider customization" width="130" height="40" /></center></p>
<pre lang='matlab'>
[jhSlider, hContainer] = javacomponent(jSlider,[10,10,100,40]);
set(jSlider, 'Value',72, 'Orientation',jSlider.VERTICAL, 'MinorTickSpacing',5);
set(hContainer,'position',[10,10,40,100]); %note container size change
</pre>
<p><center><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/003x019.png" title="JSlider customization" alt="JSlider customization" width="70" height="120" /></center><br />
We can query the current slider value via its <b>Value</b> property:</p>
<pre lang='matlab'>
>> value = get(jSlider,'Value');  % or: value = jSlider.getValue;
value =
    29
</pre>
<p>We can easily attach Matlab callback functions to slider value-change events:</p>
<pre lang='matlab'>
>> hjSlider = handle(jSlider, 'CallbackProperties')
hjSlider =
	javahandle_withcallbacks.javax.swing.JSlider
>> hjSlider.StateChangedCallback = @(hjSlider,eventData) disp(get(hjSlider,'Value'));
>> set(hjSlider, 'StateChangedCallback', @myCallback);  %alternative
</pre>
<p>As you can see, standard Java controls (such as <code>JSlider</code> here) are very simple to customize and use in Matlab GUI. I have shown more complex customizations <a target="_blank" href="/articles/javacomponent#comment-80247">elsewhere in this blog</a>, as well as in my <a target="_blank" href="/books/matlab-java">Matlab-Java programming book</a>.<br />
Note that <code>JSlider</code> (and Java sliders in general) only supports integer values, so if you need floating-point values you&#8217;d either need to find some other Java Swing component somewhere that supports what you need, or do the scaling yourself with some text label. I recently created a Matlab class wrapper for a client that does exactly that: the underlying component was a  Java slider and the labels were updated to display floating-point values, dynamically updated based on the Matlab class object&#8217;s properties. It only took a short morning to create a fully-functional generic slider class that works quite well.</p>
<h3 id="range">Range (dual-knob) sliders</h3>
<p>This brings me to my client&#8217;s query that I mentioned at the beginning of this post: <code>JSlider</code> only contains a single knob. Is it possible to integrate a range (dual-knob) slider?<br />
My initial response was to simply google for &#8220;<a target="_blank" rel="nofollow" href="https://www.google.co.il/search?q=java%20range%20slider">Java range slider</a>&#8220;. This returns numerous different controls, both open-source and commercial, that we can download and integrate in Matlab. All it takes is to download the <i>*.class, *.zip</i> or <i>*.jar</i> file that contains the component, add it to Matlab Java classpath using the <i><b><a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/javaaddpath.html">javaaddpath</a></b></i> function, and then use the <i><b>javacomponent</b></i> to display it, just as we did with <code>JSlider</code> above.<br />
This is simple enough, but then I thought of an even simpler solution, namely to use JIDE&#8217;s library of commercial-grade controls that is pre-bundled in Matlab. Surely enough, a quick search in <a target="_blank" rel="nofollow" href="http://www.jidesoft.com/javadoc/overview-summary.html">JIDE&#8217;s enormous catalog</a> yielded its <code><a target="_blank" rel="nofollow" href="http://www.jidesoft.com/javadoc/com/jidesoft/swing/RangeSlider.html">RangeSlider</a></code> component, which extends <code>JSlider</code> with a dual knob. <code>RangeSlider</code>&#8216;s appearance has changed somewhat across Matlab releases (or actually, JIDE releases, as they are integrated within the corresponding Matlab releases), but its basic functionality remained unchanged:</p>
<pre lang='matlab'>
jRangeSlider = com.jidesoft.swing.RangeSlider(0,100,20,70);  % min,max,low,high
jRangeSlider = javacomponent(jRangeSlider, [0,0,200,80], gcf);
set(jRangeSlider, 'MajorTickSpacing',25, 'MinorTickSpacing',5, 'PaintTicks',true, 'PaintLabels',true, ...
    'Background',java.awt.Color.white, 'StateChangedCallback',@myCallbackFunc);
</pre>
<p><center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="RangeSlider in R2010b" src="https://undocumentedmatlab.com/images/RangeSlider_R2010b.gif" title="RangeSlider in R2010b" width="200" height="50" /> &nbsp; <img loading="lazy" decoding="async" alt="RangeSlider in R2014b" src="https://undocumentedmatlab.com/images/RangeSlider_R2014b.gif" title="RangeSlider in R2014b" width="200" height="50" /><figcaption class="wp-caption-text"><code>RangeSlider</code> in R2010b (left), R2014b (right)</figcaption></figure></center><br />
We can move the two knobs relative to each other. We can also move the entire range (i.e., both knobs at once), by either dragging the square on top of the right knob (R2010b), or by dragging the space between the two knobs (R2014b).<br />
The benefit of JIDE controls is that they are pre-bundled in every Matlab installation and deployed MCR. There is no need to download anything, nor to use <i><b>javaaddpath</b></i>. All the richness of JIDE&#8217;s commercial-grade libraries (at least those libraries used in Matlab, which is plenty) is automatically available to us within Matlab, just as easily as the standard Java Swing controls. MathWorks has already paid a small fortune to integrate JIDE&#8217;s libraries in Matlab, and we can use it free of charge within Matlab GUIs. This is a great (and sadly undocumented) advantage of Matlab GUI. Matlab GUI programmers who wish to enrich their GUI are strongly encourages to take the time to review the long list of controls provide by JIDE in Matlab. I&#8217;ve posted <a target="_blank" href="/articles/tag/jide">quite a few articles</a> on using JIDE components in Matlab &#8211; feel free to take a look and see the richness that JIDE can bring to your GUI. Additional material can be found in my Matlab-Java programming book.<br />
In the specific case of <code>RangeSlider</code>, this control is part of the <a target="_blank" rel="nofollow" href="http://www.jidesoft.com/products/oss.htm">JIDE Common Layer</a> that JideSoft open-sourced a few years ago. This means that we can <a target="_blank" rel="nofollow" href="https://github.com/jidesoft/jide-oss">download</a> the latest version of this library and use it in Matlab, in case it has some new component that is still not available in our version of Matlab. For example, Matlab R2014b includes JIDE version 3.4.1, released by JideSoft on May 2012 &#8211; the latest version (3.6.9, released last week) includes numerous fixes and improvements that were integrated in the past 3 years:</p>
<pre lang='matlab'>
>> com.jidesoft.utils.Lm.getProductVersion
ans =
3.4.1
</pre>
<p>Note that JIDE&#8217;s online documentation (<a target="_blank" rel="nofollow" href="https://www.jidesoft.com/products/JIDE_Common_Layer_Developer_Guide.pdf">PDF</a>, <a target="_blank" rel="nofollow" href="http://www.jidesoft.com/javadoc/overview-summary.html">javadoc</a>, <a target="_blank" rel="nofollow" href="http://www.jidesoft.com/products/oss.htm">webpage</a>) always refers to the latest version. To use the latest Common-layer library in Matlab, simply <a target="_blank" rel="nofollow" href="https://github.com/jidesoft/jide-oss">download it</a> and replace Matlab&#8217;s pre-bundled <i>&lt;matlabroot&gt;/java/jarext/jide/jide-common.jar</i> file. Be careful with changing Matlab&#8217;s installation files (such as this one), as there is always a risk that some Matlab functionality might break. So always keep a copy of the original file, in case you need to revert your changes. Alternatively, place the <i>jide-common.jar</i> file in some other user folder and use it in Matlab on an as-needed basis using <i><b>javaaddpath</b></i> and <i><b>javarmpath</b></i>.<br />
Using the latest commercial (non-open-sourced) JIDE libraries, such as <i>jide-grids.jar</i>, <i>jide-components.jar</i> or <i>jide-charts.jar</i>, is only possible if you purchase them from JideSoft. But as noted, we can freely use the older bundled libraries in our Matlab GUIs without paying JideSoft anything.<br />
<b><u>Disclaimer</u></b>: I am an engineer, not a lawyer. What I said above is my personal opinion; it is not legal advice. If you are unsure about licensing of JIDE components in your programs, contact MathWorks or JideSoft.</p>
<h3 id="AppDesigner">AppDesigner &#8211; Matlab&#8217;s new GUI</h3>
<p>Last autumn, with little fanfare, MathWorks released the App Designer toolbox, which can be freely <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/48142-app-designer">downloaded from the File Exchange</a>. This is not just another File Exchange utility. It is in fact an official MathWorks <a target="_blank" rel="nofollow" href="http://www.mathworks.com/products/matlab/app-designer/tech-preview.html">Technical Preview</a> that is both functional by itself, and also provides very interesting insight of Matlab&#8217;s upcoming new GUI. MathWorks have not announced exactly when this new AppDesigner will replace the aging GUIDE in Matlab. But the fact that AppDesigner is an actual working product in the public domain since late 2014, and that MathWorks has officially endorsed it as a &#8220;Technical Preview&#8221;, mean that this day is close.<br />
In the new AppDesigner, sliders finally appear modern, complete with all sorts of customizable properties:<br />
<center><figure style="width: 598px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Sliders in Matlab's new AppDesigner" src="https://undocumentedmatlab.com/images/slider_AppDesigner.png" title="Sliders in Matlab's new AppDesigner" width="598" height="376" /><figcaption class="wp-caption-text">Sliders in Matlab's new AppDesigner</figcaption></figure></center><br />
Java controls still provide more customizability than Matlab, even in the new AppDesigner, but the functionality gap is now significantly reduced. This provides the flexibility of modern easy-to-create/maintain GUIs for users who do not need to preserve backward-compatibility with existing GUIs or extra customizabilty enabled by Java, while preserving the functionality for those who do.<br />
Java components and even standard Matlab <i><b>uicontrol</b></i>s cannot be added to an AppDesigner window because it is not a standard Java <code>JFrame</code> window. The new App window has its own set of controls, separate from <i><b>uicontrols</b></i> (topic for a separate blog post someday). However, we can always keep using <i><b>javacomponent</b></i> and <i><b>uicontrol</b></i> in plain-ol&#8217; figures, as before, side-by-side with the new AppDesigned windows. The new App window can be created using the new <i><b>appwindow</b></i> function, whereas the existing <i><b>figure</b></i> function creates a standard figure window (basically a Java <code>JFrame</code>) that accepts <i><b>javacomponent</b></i> and <i><b>uicontrol</b></i>. Maybe one day I&#8217;ll find out if there&#8217;s a way to combine these two seemingly disparate sets of GUIs. In the meantime I&#8217;m content that there&#8217;s a new way to create Matlab GUIs that has not previously existed.<br />
AppDesigner is a very nice addition for Matlab GUI builders, and it will get even better with time. Having looked at some of the internals, I&#8217;m drooling over the potential improvements. MathWorks has invested quite a bit in this new product, so I&#8217;m confident that many of these improvements will find their way into AppDesigner in the upcoming releases. I just hope it will remain a free utility and will not turn into an addon toolbox when officially released (I have not seen any mention about this either way, so it&#8217;s still an open question; I&#8217;ll clarify this point here when I learn something). For the time being, AppDesigner is free to use.<br />
MathWorks is actively looking for ways to improve AppDesigner, so if you find any functionality that is missing or buggy, please provide feedback:<br />
<center><figure style="width: 280px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Feedback for Matlab's new AppDesigner" src="http://www.mathworks.com/images/nextgen/supporting/products/matlab-app-designer/feedback.png" title="Feedback for Matlab's new AppDesigner" width="280" height="143" /><figcaption class="wp-caption-text">Feedback for Matlab's new AppDesigner</figcaption></figure></center></p>
<h3 id="conclusions">Conclusions and some personal musings</h3>
<p>Matlab itself has kept its Desktop GUI relatively modern, and integrates advanced JIDE GUI controls internally. But until AppDesigner came about, Matlab application builders were not provided with similarly modern documented GUI components and design tools, in keeping with the times.<br />
It is indeed possible, as I&#8217;ve <a target="_blank" href="/articles/auto-completion-widget">repeatedly claimed</a> in this blog, to create professional-looking GUIs in Matlab. However, this currently requires using undocumented features and Java controls.<br />
In Matlab&#8217;s upcoming AppDesigner, making professional-looking Matlab GUIs will be easier, with sleek new controls, user-friendly visual layout, and easy-to-maintain class-based code. I still find the tech-preview to be lacking in some respects, and not integrated with the existing GUI functionality. Still, the fact that MathWorks has gone out of its way to provide a Technical Preview of its upcoming new GUI, despite its normal reluctance to provide a technical development roadmap, shows a commitment to improving Matlab&#8217;s user-facing front-end. This makes me optimistic that most shortcomings will be solved by the time AppDesigner is officially released, hopefully soon.<br />
Until this happens, and possibly even later, we can significantly improve Matlab&#8217;s standard GUI using Java in standard figure windows. Interested readers can find out more information about integrating Java controls in Matlab GUI in my book &#8220;<i><b><a target="_blank" href="/books/matlab-java">Undocumented Secrets of MATLAB-Java Programming</a></b></i>&#8221; (CRC Press, 2011, ISBN 978-1439869031). If you already have this book, please be kind enough to post your feedback on it on Amazon (<a target="_blank" rel="nofollow" href="http://www.amazon.com/Undocumented-Secrets-MATLAB-Java-Programming-Altman/product-reviews/1439869030?sortBy=bySubmissionDateDescending#productSummary">link</a>), for the benefit of others.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/sliders-in-matlab-gui">Sliders in Matlab GUI</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2" rel="bookmark" title="Sliders in Matlab GUI &#8211; part 2">Sliders in Matlab GUI &#8211; part 2 </a> <small>Matlab contains a variety of ways to define/display slider controls in GUI windows. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-spinners-in-matlab-gui" rel="bookmark" title="Using spinners in Matlab GUI">Using spinners in Matlab GUI </a> <small>Spinner controls can easily be added to Matlab GUI. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/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>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/sliders-in-matlab-gui/feed</wfw:commentRss>
			<slash:comments>59</slash:comments>
		
		
			</item>
		<item>
		<title>Unorthodox checkbox usage</title>
		<link>https://undocumentedmatlab.com/articles/unorthodox-checkbox-usage?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=unorthodox-checkbox-usage</link>
					<comments>https://undocumentedmatlab.com/articles/unorthodox-checkbox-usage#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 14 Jan 2015 21:41:18 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Optical illusion]]></category>
		<category><![CDATA[uicontrol]]></category>
		<category><![CDATA[uisplitpane]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5457</guid>

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

					<description><![CDATA[<p>Matlab combobox (dropdown) popups can be customized in a variety of ways. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-combobox-popups">Customizing combobox popups</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items" rel="bookmark" title="Customizing listbox/combobox items">Customizing listbox/combobox items </a> <small>Matlab listboxes can be customized using custom Java cell-renderers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-editbox-scrollbars" rel="bookmark" title="Customizing listbox &amp; editbox scrollbars">Customizing listbox &amp; editbox scrollbars </a> <small>Matlab listbox and multi-line editbox uicontrols have pre-configured scrollbars. This article shows how they can be customized....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-3" rel="bookmark" title="Customizing menu items part 3">Customizing menu items part 3 </a> <small>Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Last week I explained how we can use display <a target="_blank" href="/articles/customizing-listbox-combobox-items">custom items in a standard Matlab combobox</a> (popup/dropdown), using its underlying Java component. Today I will show how we can use this Java component for other nice customizations of the combobox&#8217;s popup:<br />
<span class="alignleft"><img loading="lazy" decoding="async" alt="" src="https://undocumentedmatlab.com/images/popup2a.png" title="" width="86" height="98" /></span></p>
<ul>
<li><a href="/articles/customizing-combobox-popups#underlying">Getting the underlying Java component</a></li>
<li><a href="/articles/customizing-combobox-popups#MaximumRowCount">MaximumRowCount</a></li>
<li><a href="/articles/customizing-combobox-popups#PopupVisible">PopupVisible</a></li>
<li><a href="/articles/customizing-combobox-popups#PopupWidthConstrained">PopupWidthConstrained</a></li>
</ul>
<p><span id="more-5056"></span></p>
<h3 id="underlying">Underlying Java component</h3>
<p>The first step is to find the underlying Java component of the Matlab combobox (aka popup) uicontrol. This is done using my <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/14317-findjobj-find-java-handles-of-matlab-graphic-objects"><i><b>findjobj</b></i> utility</a>:</p>
<pre lang='matlab'>
% Create the Matlab combobox
items = {'<html><font color="red">Hello</font></html>', 'world', ...
         '<html><font style="font-family:impact;color:green"><i>What a', ...
         '<html><font color="blue" face="Comic Sans MS">nice day!</font>'};
hCombobox = uicontrol('Style','popup', 'Position',[10,100,120,20], 'String',items);
% Find the uicontrol's underlying Java component
jCombobox = findjobj(hCombobox);
</pre>
<p>For <i><b>findjobj</b></i> to work, the Matlab uicontrol needs to be visible &#8211; it will not have a Java component before it is rendered onscreen for the first time. If everything is successful, jCombobox should now be a reference to the underlying <code>om.mathworks.hg.peer.ComboboxPeer$MLComboBox</code> Java component, which is an extension of the standard Swing <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/7/docs/api/javax/swing/JComboBox.html"><code>JComboBox</code></a>, as can be seen using my <a target="_blank" href="/articles/checkclass"><i><b>checkClass</b></i> utility</a>:</p>
<pre lang='matlab'>
>> jCombobox.checkClass
private com.mathworks.hg.peer.ComboboxPeer$MLComboBox (uiinspect)
Superclass: com.mathworks.mwswing.MJComboBox
Superclass: javax.swing.JComboBox
Methods in JComboBox missing in ComboboxPeer$MLComboBox:
   JComboBox()
   JComboBox(java.lang.Object[])
   JComboBox(java.util.Vector)
   JComboBox(javax.swing.ComboBoxModel)
Methods in ComboboxPeer$MLComboBox missing in JComboBox:
   ComboboxPeer$MLComboBox(com.mathworks.hg.peer.ComboboxPeer)
   isPopupWidthConstrained() : boolean
   isTipWhenTruncatedEnabled() : boolean
   processEvent(java.awt.AWTEvent)
   registerWithKeyBindingManager(com.mathworks.mwswing.binding.KeyBindingManager, java.lang.String)
   setConstrainPopupWidth(boolean)
   setEditorColumnCount(int)
   setTipWhenTruncatedEnabled(boolean)
Methods inherited & modified by ComboboxPeer$MLComboBox:
   getInsets() : java.awt.Insets
   setBackground(java.awt.Color)
   updateUI()
Interfaces in JComboBox missing in ComboboxPeer$MLComboBox:
   java.awt.ItemSelectable
   java.awt.event.ActionListener
   javax.accessibility.Accessible
   javax.swing.event.ListDataListener
</pre>
<p>We shall now use three properties of this object to customize the control&#8217;s popup:</p>
<h3 id="MaximumRowCount">MaximumRowCount</h3>
<p>The <b>MaximumRowCount</b> numeric property (default=20) sets the maximal number of drop-down items to display in the visible portion of the popup, before requiring a scrollbar. This basically controls the popup&#8217;s height:</p>
<pre lang='matlab'>
% Get the current MaximumRowCount value
numItems = get(jCombobox, 'MaximumRowCount');
numItems = jCombobox.MaximumRowCount;     % equivalent - access the property directly
numItems = jCombobox.getMaximumRowCount;  % equivalent - use Java's accessor method (best way)
% Set the MaximumRowCount value
set(jCombobox,'MaximumRowCount',3);
jCombobox.MaximumRowCount = 3;      % equivalent - access the property directly
jCombobox.setMaximumRowCount(3);    % equivalent - use Java's accessor method (best way)
</pre>
<p><center></p>
<div class="wp-caption aligncenter" style="width: 150px; background-color: white;"><img loading="lazy" decoding="async" alt="MaximumRowCount=20 (default)" src="https://undocumentedmatlab.com/images/popup2a.png" title="MaximumRowCount=20 (default)" width="86" height="98"></p>
<p class="wp-caption-text"><b>MaximumRowCount</b>=20<br />(default)</p>
</div>
<div class="wp-caption aligncenter" style="width: 140px; background-color: white;"><img loading="lazy" decoding="async" alt="MaximumRowCount=3" src="https://undocumentedmatlab.com/images/popup2b.png" title="MaximumRowCount=3" width="83" height="77"></p>
<p class="wp-caption-text"><b>MaximumRowCount</b>=3<br />&nbsp;</p>
</div>
<div class="wp-caption aligncenter" style="width: 140px; background-color: white;"><img loading="lazy" decoding="async" alt="MaximumRowCount=2" src="https://undocumentedmatlab.com/images/popup2c.png" title="MaximumRowCount=2" width="84" height="73"></p>
<p class="wp-caption-text"><b>MaximumRowCount</b>=2<br />&nbsp;</p>
</div>
<p></center><br />
Note that <b>MaximumRowCount</b> is a Matlab extension to the standard Swing <code>JComboBox</code>, so if we use a <code>JComboBox</code> directly in our code (using <a target="_blank" href="/articles/javacomponent"><i><b>javacomponent</b></i></a>) we will not have this feature. Creating the <code>ComboboxPeer$MLComboBox</code> component instead is possible, but is beyond the scope of this article, because MathWorks chose for this class not to have <code>JComboBox</code>&#8216;s standard constructors but rather only a constructor that accepts a <code>com.mathworks.hg.peer.ComboboxPeer</code> object.</p>
<h3 id="PopupVisible">PopupVisible</h3>
<p>The <b>PopupVisible</b> property (default=false) is a boolean flag which controls whether the popup window is currently (or should be) displayed. If this property is updated, then the focus is automatically transferred to the popup window for easy item selection using the keyboard (up/down/enter keys). There are also equivalent convenience methods <i>showPopup()/hidePopup()</i>:</p>
<pre lang='matlab'>
% Is the popup currently shown?
isShown = get(jCombobox, 'PopupVisible');
isShown = jCombobox.PopupVisible;     % equivalent - access the property directly
isShown = jCombobox.isPopupVisible;   % equivalent - use Java's accessor method (best way)
% Display the popup
set(jCombobox,'PopupVisible',true);   % NOT 'on' - this is a Java property, not a Matlab HG one!
jCombobox.PopupVisible = true;        % equivalent - access the property directly
jCombobox.setPopupVisible(true);      % equivalent - use Java's accessor method (best way)
jCombobox.showPopup();                % equivalent - use Java's direct method
% Hide the popup
set(jCombobox,'PopupVisible',false);  % NOT 'off' - this is a Java property, not a Matlab HG one!
jCombobox.PopupVisible = false;       % equivalent - access the property directly
jCombobox.setPopupVisible(false);     % equivalent - use Java's accessor method (best way)
jCombobox.hidePopup();                % equivalent - use Java's direct method
</pre>
<p>Note that <b>PopUpVisible</b> is not a Matlab extension &#8211; it exists in the original Swing <code>JComboBox</code>. Unfortunately, it was not included in the list of properties that are exposed to the user by the high-level Matlab uicontrol, so we need to use the underlying Java component.<br />
On a Windows platform the <b>PopupVisible</b> property is toggled, thereby showing/hiding the popup window, whenever the user clicks &lt;Alt-Up&gt; or &lt;Alt-Down&gt; when the combo-box has focus.</p>
<h3 id="PopupWidthConstrained">PopupWidthConstrained</h3>
<p>The <b>PopupWidthConstrained</b> property (default=false) is a boolean flag which is another Matlab extension to the standard Swing <code>JComboBox</code>. It is apparently used to constrain the width of the drop-down list to the width of the text field. MathWorks took the trouble to add this feature because Swing <code>JComboBox</code>&#8216;s width is constrained, causing a difficulty in distinguishing between popup values when the control is relatively narrow; Matlab&#8217;s <code>MJComboBox</code>&#8216;s default unconstrained behavior is much more user-friendly:<br />
<center></p>
<div class="wp-caption aligncenter" style="width: 180px; background-color: white;"><img loading="lazy" decoding="async" alt="PopupWidthConstrained=false (default)" src="https://undocumentedmatlab.com/images/popup_WidthConstrained2.png" title="PopupWidthConstrained=false (default)" width="79" height="92"></p>
<p class="wp-caption-text"><b>PopupWidthConstrained</b>=false<br />(default)</p>
</div>
<div class="wp-caption aligncenter" style="width: 180px; background-color: white;"><img loading="lazy" decoding="async" alt="PopupWidthConstrained=true" src="https://undocumentedmatlab.com/images/popup_WidthConstrained.png" title="PopupWidthConstrained=true" width="60" height="92"></p>
<p class="wp-caption-text"><b>PopupWidthConstrained</b>=true<br />&nbsp;</p>
</div>
<p></center><br />
Note that the <b>PopupWidthConstrained</b> property&#8217;s read accessor methods is the expected <i>isPopupWidthConstrained()</i>, thereby also enabling the expected Matlab-standard format of <i><b>get</b>(&#8216;PopupWidthConstrained&#8217;)</i>. However, the property update accessor method is not the expected <i>setPopupWidthConstrained(flag)</i> but rather a non-standard <i>setConstrainPopupWidth(flag)</i>. For this reason, it is impossible to set this property using <i><b>set</b>(&#8216;PopupWidthConstrained&#8217;,…)</i>, but only via the Java <i>setConstrainPopupWidth()</i> accessor method:</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">set</span><span style="color: #080;">(</span>jCombobox,<span style="color:#A020F0;">'PopupWidthConstrained'</span>,<span style="color: #0000FF;">true</span><span style="color: #080;">)</span>
<span style="color:red">??? Changing the 'PopupWidthConstrained' property of javahandle_withcallbacks.com.mathworks.hg.peer.ComboboxPeer$MLComboBox is not allowed.</span>
&nbsp;
&gt;&gt; jCombobox.<span style="">setPopupWidthConstrained</span><span style="color: #080;">(</span><span style="color: #0000FF;">true</span><span style="color: #080;">)</span>
<span style="color:red">??? No appropriate method or public field setPopupWidthConstrained for class javahandle_withcallbacks.com.mathworks.hg.peer.ComboboxPeer$MLComboBox.</span>
&nbsp;
&gt;&gt; jCombobox.<span style="">setConstrainPopupWidth</span><span style="color: #080;">(</span><span style="color: #0000FF;">true</span><span style="color: #080;">)</span>  <span style="color: #228B22;">% this is ok</span></pre>
</div>
</div>
<p>For additional customizations of Matlab comboboxes, refer to section 6.7 of my <a target="_blank" href="/matlab-java-book">Matlab-Java programming book</a>.</p>
<h3 id="R2014b">R2014b</h3>
<p>We&#8217;re all eagerly awaiting the much-anticipated R2014b release. As you all know, this is an important release with major functionality and engine improvements. It is therefore not surprising that the release date (which should normally have been September 1) is somewhat delayed. MathWorkers are hard at work fixing problems in the pre-release beta. This delay was actually anticipated, as can be seen from the pre-release expiry date.<br />
We should all be patient and let MathWorks fix these issues without pressure. This release could be a real home-run and MathWorks should do all it can to ensure that it works as transparently and as backward-compatible as possible so that it indeed becomes a home run rather than an outfield foul ball. Let&#8217;s not have a repeat of R2010b, which required two separate service-pack updates. I urge MathWorks to take their time &#8211; better safe than sorry. I urge everyone else to be patient &#8211; it&#8217;s worth the wait.<br />
When 14b is finally out, I will be here with a planned series of articles explaining how we can make good use of all its new goodies. Start drooling&#8230;<br />
Happy Jewish New Year everybody! </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-combobox-popups">Customizing combobox popups</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items" rel="bookmark" title="Customizing listbox/combobox items">Customizing listbox/combobox items </a> <small>Matlab listboxes can be customized using custom Java cell-renderers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-editbox-scrollbars" rel="bookmark" title="Customizing listbox &amp; editbox scrollbars">Customizing listbox &amp; editbox scrollbars </a> <small>Matlab listbox and multi-line editbox uicontrols have pre-configured scrollbars. This article shows how they can be customized....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-3" rel="bookmark" title="Customizing menu items part 3">Customizing menu items part 3 </a> <small>Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-combobox-popups/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing listbox/combobox items</title>
		<link>https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-listbox-combobox-items</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 17 Sep 2014 12:01:34 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Icons]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[uicontrol]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5029</guid>

					<description><![CDATA[<p>Matlab listboxes can be customized using custom Java cell-renderers. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items">Customizing listbox/combobox items</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-combobox-popups" rel="bookmark" title="Customizing combobox popups">Customizing combobox popups </a> <small>Matlab combobox (dropdown) popups can be customized in a variety of ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-3" rel="bookmark" title="Customizing menu items part 3">Customizing menu items part 3 </a> <small>Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-editbox-scrollbars" rel="bookmark" title="Customizing listbox &amp; editbox scrollbars">Customizing listbox &amp; editbox scrollbars </a> <small>Matlab listbox and multi-line editbox uicontrols have pre-configured scrollbars. This article shows how they can be customized....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-2" rel="bookmark" title="Customizing menu items part 2">Customizing menu items part 2 </a> <small>Matlab menu items can be customized in a variety of useful ways using their underlying Java object. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Last week I <a target="_blank" href="/articles/checkboxlist">wrote</a> about using a variety of techniques to customize listbox items with an attached checkbox icon. Some of these methods used a standard Matlab listbox uicontrol, others used other controls. Today I wish to extend the discussion and show how Matlab listbox and combobox (pop-up) items can be customized in a variety of ways.<br />
To add icons to listbox/combobox items, we could use standard HTML, as I&#8217;ve shown last week. This is the simplest method, requires no Java knowledge, and it usually works well. The problem is that when a listbox/combobox has numerous items (hundreds or more), it may start getting sluggish. In such case it is faster to use a dedicated Java cell-renderer that sets the icon, font, colors, tooltip and other aspects on an item-by-item basis. This runs faster and enables far greater customizability than what is possible with HTML. The drawback is that it requires some Java programming. No free lunch&#8230;<br />
Listbox and combobox cell-renderers need to extend <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/javax/swing/ListCellRenderer.html"><code>javax.swing.ListCellRenderer</code></a>, similarly to <a target="_blank" href="/articles/uitable-cell-colors#colors">uitable cell-renderers</a>. This is basically a simple Java class that minimally contains just an empty constructor and a <i>getListCellRendererComponent()</i> method with a predefined signature. <i>getListCellRendererComponent()</i> is automatically called by the Swing render engine separately for each listbox item, and gets as input args a <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/javax/swing/JList.html"><code>JList</code></a> reference, the item value (typically a string), an integer list index, a boolean flag indicating whether the item is currently selected, and another flag indicating whether the item is currently in focus. <i>getListCellRendererComponent()</i> uses these parameters to customize and return a <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/java/awt/Component.html"><code>java.awt.Component</code></a>, which is typically (but not necessarily) a standard Swing <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/javax/swing/JLabel.html"><code>JLabel</code></a>.<br />
Here is a simple example that displays a folder of icon files in a Matlab listbox and combobox. Each item is the filename, with a customization that if the file is an icon, then this icon is displayed next to the file name, otherwise the name appears in <font color="red"><i>red italic</i></font> without an icon. For illustration, we&#8217;ll use Matlab&#8217;s builtin icons folder: <i>%matlabroot%/toolbox/matlab/icons/</i>:<br />
<center><img loading="lazy" decoding="async" alt="Custom listbox cell-renderer" src="https://undocumentedmatlab.com/images/LabelListBoxRenderer.gif" title="Custom listbox cell-renderer" width="124" height="154" /> &nbsp;&nbsp; <img loading="lazy" decoding="async" alt="Custom combobox cell-renderer" src="https://undocumentedmatlab.com/images/LabelListBoxRenderer2.gif" title="Custom combobox cell-renderer" width="482" height="150" /></center><br />
<span id="more-5029"></span></p>
<h3 id="renderer">Creating the cell renderer</h3>
<p>We start by creating a custom <code>ListCellRenderer</code>. Place the following code in a file called <a target="_blank" href="http://files.undocumentedmatlab.com/LabelListBoxRenderer.java"><i>LabelListBoxRenderer.java</i></a>:</p>
<pre lang='java'>
import java.awt.*;
import javax.swing.*;
import java.util.Hashtable;
public class LabelListBoxRenderer extends JLabel implements ListCellRenderer
{
    private String folderPath;
    private final Hashtable<string,ImageIcon> iconsCache = new Hashtable<string,ImageIcon>();
    // Class constructors
    public LabelListBoxRenderer() {
        setOpaque(true);
        setHorizontalAlignment(LEFT);
        setVerticalAlignment(CENTER);
    }
    public LabelListBoxRenderer(String folderPath) {
        this();
        this.folderPath = folderPath;
    }
    // Return a label displaying both text and image.
    public Component getListCellRendererComponent(
            JList list,
            Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus)
    {
        String label = value.toString();
        setFont(list.getFont());
        if (isSelected) {
            // Selected cell item
            setBackground(list.getSelectionBackground());
            setForeground(list.getSelectionForeground());
        } else {
            // Unselected cell item
            setBackground(list.getBackground());
            setForeground(list.getForeground());
        }
        try {
            String iconFname = (folderPath + "/" + label).replace('\\', '/');
            ImageIcon icon = getFileIcon(iconFname);
            setIcon(icon);
            if (icon.getIconWidth() > 0) {
                // Cell item is a valid icon filename
                list.setToolTipText(iconFname + " (" + icon.getIconWidth() + " x " + icon.getIconHeight() + ")");
            } else {
                // Cell item is not an icon filename
                list.setToolTipText(iconFname + " (not an icon)");
                setFont(getFont().deriveFont(Font.ITALIC));
                setForeground(Color.red);
            }
        } catch (Exception e) {
            list.setToolTipText(e.getMessage());
        }
        //System.out.println(index + ": " + label);  // debug console printout
        setText(label);
        return this;
    }
    // Modify the folder path (default = current folder)
    public void setFolderPath(String folderPath) {
        this.folderPath = folderPath;
    }
    // Lazily load the file icons only as needed, later reuse cached data
    private ImageIcon getFileIcon(String filename) {
        ImageIcon icon;
        if (iconsCache.containsKey(filename)) {
            // Reuse cached data
            icon = iconsCache.get(filename);
        } else {
            // Lazily load the file icons only as needed
            icon = new ImageIcon(filename);
            iconsCache.put(filename, icon);  // store in cache for later use
        }
        return icon;
    }
}
</pre>
<p>In the code above, I&#8217;ve cached the <code>ImageIcons</code>, so that the actual disk file is only accessed once rather than repeatedly whenever the cell needs to be rendered. For even improved performance, we could also cache the tooltips and derived italic font so that they would not be regenerated each time (note that the list&#8217;s font is not the same as the cell component&#8217;s font) &#8211; I will leave this as an exercise to the reader.<br />
Next, compile this file (using the standard javac compiler or any Java IDE), ensuring that you target a JVM compatible with your Matlab (JVM 5 will work on R14SP2 onward, 6 on R2007b onward, and 7 only on R2013b or newer). For convenience, both the source and compiled files for the LabelListBoxRenderer class can be downloaded here: <a target="_blank" href="http://files.undocumentedmatlab.com/LabelListBoxRenderer.java"><i>LabelListBoxRenderer.java</i></a>, <a target="_blank" href="http://files.undocumentedmatlab.com/LabelListBoxRenderer.class"><i>LabelListBoxRenderer.class</i></a>.</p>
<h3 id="listbox">Using the cell-renderer in Matlab listboxes</h3>
<p>Now that we have a custom cell renderer, we should add the <i>LabelListBoxRenderer.class</i> file to Matlab&#8217;s Java classpath using the <i><b>javaaddpath</b></i> function and then use this class in Matlab:</p>
<pre lang='matlab'>
% Create the Matlab listbox
iconsFolder = fullfile(matlabroot, 'toolbox/matlab/icons');
files = dir(iconsFolder);
hListbox = uicontrol('Style','list', 'String',{files.name}, 'Position',[10,10,120,150]);
% Find the uicontrol's underlying Java component
jScrollpane = findjobj(hListbox);
jListbox = jScrollpane.getViewport.getView;
% Update the listbox's cell-renderer
javaaddpath 'C:\Yair\Undocumented Matlab\Work\'   % location of my LabelListBoxRenderer.class
jRenderer = LabelListBoxRenderer(iconsFolder);
jListbox.setCellRenderer(jRenderer);
% Give the icons some space...
jListbox.setFixedCellHeight(18);
</pre>
<p><center><img loading="lazy" decoding="async" alt="Custom listbox cell-renderer" src="https://undocumentedmatlab.com/images/LabelListBoxRenderer.gif" title="Custom listbox cell-renderer" width="124" height="154" /></center><br />
Wasn&#8217;t too painful was it?</p>
<h3 id="combobox">Using the cell-renderer in Matlab combo-boxes</h3>
<p>Customizing Matlab combo-boxes is just as easy, and uses the same LabelListBoxRenderer class:</p>
<pre lang='matlab'>
% Create the Matlab combobox
iconsFolder = fullfile(matlabroot, 'toolbox/matlab/icons');
files = dir(iconsFolder);
hCombobox = uicontrol('Style','popup', 'String',{files.name}, 'Position',[10,10,120,150]);
% Find the uicontrol's underlying Java component
jCombobox = findjobj(hCombobox);  % no scroll-pane for combos
% Update the combobox's cell-renderer
javaaddpath 'C:\Yair\Undocumented Matlab\Work\'   % location of my LabelListBoxRenderer.class
jRenderer = LabelListBoxRenderer(iconsFolder);
jCombobox.setRenderer(jRenderer);  % Note: not setCellRenderer()
% Give the icons some space...
jCombobox.setFixedCellHeight(18);
% Make the drop-down list shorter than the default (=20 items)
jCombobox.setMaximumRowCount(8);
</pre>
<p><center><img loading="lazy" decoding="async" alt="Custom combobox cell-renderer" src="https://undocumentedmatlab.com/images/LabelListBoxRenderer2.gif" title="Custom combobox cell-renderer" width="482" height="150" /></center><br />
For additional aspects of listbox and combobox customizations, refer to sections 6.6 and 6.7 of my <a target="_blank" href="/matlab-java-book">Matlab-Java programming book</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items">Customizing listbox/combobox items</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-combobox-popups" rel="bookmark" title="Customizing combobox popups">Customizing combobox popups </a> <small>Matlab combobox (dropdown) popups can be customized in a variety of ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-3" rel="bookmark" title="Customizing menu items part 3">Customizing menu items part 3 </a> <small>Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-listbox-editbox-scrollbars" rel="bookmark" title="Customizing listbox &amp; editbox scrollbars">Customizing listbox &amp; editbox scrollbars </a> <small>Matlab listbox and multi-line editbox uicontrols have pre-configured scrollbars. This article shows how they can be customized....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-menu-items-part-2" rel="bookmark" title="Customizing menu items part 2">Customizing menu items part 2 </a> <small>Matlab menu items can be customized in a variety of useful ways using their underlying Java object. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-listbox-combobox-items/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Undocumented button highlighting</title>
		<link>https://undocumentedmatlab.com/articles/undocumented-button-highlighting?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=undocumented-button-highlighting</link>
					<comments>https://undocumentedmatlab.com/articles/undocumented-button-highlighting#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 05 Feb 2014 16:00:48 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[GUIDE]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[uicontrol]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4635</guid>

					<description><![CDATA[<p>Matlab button uicontrols can easily be highlighted by simply setting their Value property. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-button-highlighting">Undocumented button highlighting</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/borderless-button-used-for-plot-properties" rel="bookmark" title="Borderless button used for plot properties">Borderless button used for plot properties </a> <small>A borderless button can be used to add unobtrusive functionality to plot axes...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/toolbar-button-labels" rel="bookmark" title="Toolbar button labels">Toolbar button labels </a> <small>GUI toolbar button labels can easily be set and customized using underlying Java components. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/button-customization" rel="bookmark" title="Button customization">Button customization </a> <small>Matlab's button uicontrols (pushbutton and togglebutton) are basically wrappers for a Java Swing JButton object. This post describes how the buttons can be customized using this Java object in ways that are impossible using pure Matlab....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/hgs-undocumented-parameters-interface" rel="bookmark" title="HG&#039;s undocumented parameters interface">HG&#039;s undocumented parameters interface </a> <small>Some HG functions also accept inputs parameters in a struct fields rather than the normal P-V pairs format. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>One of my consulting clients approached me yesterday with a mystery: In his GUIDE-generated GUI, one of the buttons had a bluish tint, and no obvious property seemed to control this or to differentiate it from its sibling controls. Here&#8217;s a parred-down version of his GUI:<br />
<center><figure style="width: 225px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Highlighted GUI button" src="https://undocumentedmatlab.com/images/button_highlight1.png" title="Highlighted GUI button" width="225" height="25" /><figcaption class="wp-caption-text">Highlighted GUI button</figcaption></figure></center><br />
So while it was very nice to have a highlighted button in this manner, the fact that he did not know why it happened and how to control it was a bit unsettling. Which is where I came in, and it turns out that the solution to the mystery is simple and very easy to use. My client now happily switches button highlights on and off, just for the fun of it&#8230;<br />
Before I describe the solution (spoiler alert: scroll down), I think it is instructional to understand the unsuccessful attempts, so here goes:<br />
<span id="more-4635"></span></p>
<h3 id="alternatives">Various alternatives</h3>
<p>Our first attempts to understand the situation were to modify the button control&#8217;s obvious suspect properties:</p>
<ul>
<li><b>String</b> &#8211; the button had an <a target="_blank" href="/articles/button-customization/">HTML label</a>. One might presume that this caused the highlighting tint, perhaps an <a target="_blank" href="/articles/images-in-matlab-uicontrols-and-labels/">HTML image</a> painted the background? <a target="_blank" href="/articles/html-support-in-matlab-uicomponents/">HTML labels for uicontrols</a> are really cool so it would be a pity to have to stop using them. Fortunately, replacing the HTML label with a simple string had no effect, so we can keep using HTML labels safely and freely. But we&#8217;re still left with our mystery, so moving on&#8230;</li>
<li><b>Border</b> &#8211; yet another suspect: the <a target="_blank" href="/articles/customizing-uicontrol-border/">control&#8217;s border</a> and <a target="_blank" href="/articles/borderless-button-used-for-plot-properties/">fly-over appearance feature</a> affects its appearance. This also proved a dead-end: all the buttons had simple default borders, nothing special about the highlighted one.</li>
<li><b>Background</b> &#8211; another dead end: while we could indeed set a non-standard button color, this property does not enable the tinting effect (lighter half at top, darker at bottom). Needless to say, in our case this property had the default (gray) value.</li>
<li><b>Selected</b> &#8211; this property does not really highlight the control, but rather draws a thick dashed border around it (see below).</li>
<li>focus &#8211; by calling <i><b>uicontrol</b>(hButton)</i> we can have Matlab set the focus on the button. The Operating System then automatically kicks in to add some shading effect. This finally looked close, but again, it was just not quite right.</li>
</ul>
<p><center><figure style="width: 240px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Highlight (left); focus (center); Selected (right)" src="https://undocumentedmatlab.com/images/button_highlight2.png" title="Highlight (left); focus (center); Selected (right)" width="230" height="30" /><figcaption class="wp-caption-text">Highlight (left); focus (center); Selected (right)</figcaption></figure></center></p>
<h3 id="highlighting">Solution of the highlighting mystery</h3>
<p>So maybe GUIDE attached some funky property value to the control? Let&#8217;s investigate. Remembering that the GUIDE-generated <a target="_blank" href="/articles/fig-files-format/">*.fig file is simply a standard MAT file</a> with a different extension, we can load it into the Matlab workspace and dissect it. Drilling down the GUI hierarchy we find:</p>
<pre lang='matlab' highlight='11'>
>> data = load('myGUI.fig', '-mat')
data =
    hgS_070000: [1x1 struct]
>> d.hgS_070000.children(9).properties
ans =
              Units: 'pixels'
           Callback: [function_handle]
           Position: [20 20 60 20]
             String: 'Yes'
              Value: 1
    ApplicationData: [1x1 struct]
>> d.hgS_070000.children(10).properties
ans =
              Units: 'pixels'
           Callback: [function_handle]
           Position: [100 20 60 20]
             String: 'No'
    ApplicationData: [1x1 struct]
</pre>
<p>When we compare the information that GUIDE stored for the two buttons we see that it stored an extra Value property for the &#8216;Yes&#8217; button, and used the <a target="_blank" href="/articles/getting-default-hg-property-values/">default HG value</a> for the &#8216;No&#8217; button. Let&#8217;s compare the property values in run-time (I&#8217;m using my <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/14395-objdiff-generic-object-comparator">objDiff utility</a> for this):</p>
<pre lang='matlab' highlight='10'>
>> hButton1 = findall(gcf, 'String', 'Yes');
>> hButton2 = findall(gcf, 'String', 'No');
>> props1 = get(hButton1);
>> props2 = get(hButton2);
>> objdiff(props1, props2)
ans =
      Extent: {[0 0 24 19]  [0 0 17 19]}
    Position: {[20 20 60 20]  [100 20 60 20]}
      String: {'Yes'  'No'}
       Value: {[1]  [0]}
</pre>
<p>This pretty much nails it: pushbutton highlighting is controlled via the <b>Value</b> property. According to the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/uicontrol_props.html#bqxoir7">official documentation</a>, the <b>Value</b> property has no meaning for push-buttons, only for other uicontrol styles. This is obviously not so:</p>
<pre lang='matlab'>
set(hButton, 'Value', 1);   % Turn button highlighting on
set(hButton, 'Value', 0);   % Turn button highlighting off (can use any value ~=1)
</pre>
<h3 id="Technical">Under the hood</h3>
<p>Under the hood, updating the <b>Value</b> property sets the pushbutton&#8217;s <a target="_blank" href="/articles/findjobj-find-underlying-java-object/">underlying Java control</a>&#8216;s <b>Selected</b> property to true. Note that the Java <b>Selected</b> property is entirely unrelated to Matlab&#8217;s <b>Selected</b> property (which has no underlying Java counterpart). I do not understand the design decision that let to this, but since it has been like this for many years I see little chance that it will be changed in the near future.<br />
In any case, the Java <b>Selected</b> property indeed has a visual effect, but the actual effect depends on the current operating system and Look-&amp;-Feel (LnF). You can <a target="_blank" href="/articles/modifying-matlab-look-and-feel/">play around with the LnF</a> to achieve various other alternative highlighting effects, or customize one of your own.</p>
<h3 id="seminar">Advanced Matlab GUI course &#8211; London 12-14 March, 2014</h3>
<p>If this topic has piqued your interest, consider joining my <a target="_blank" href="/training/advanced-matlab-seminars-london-10-14-march-2014/">Advanced Matlab GUI course</a> in London on 12-14 March, 2014. In this course/seminar I will explore numerous other ways by which we can customize Matlab&#8217;s GUI and graphics in ways that you never knew were even possible! This is a unique opportunity to take your Matlab skills to a higher level within just a few days. This training is not offered anywhere else.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-button-highlighting">Undocumented button highlighting</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/borderless-button-used-for-plot-properties" rel="bookmark" title="Borderless button used for plot properties">Borderless button used for plot properties </a> <small>A borderless button can be used to add unobtrusive functionality to plot axes...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/toolbar-button-labels" rel="bookmark" title="Toolbar button labels">Toolbar button labels </a> <small>GUI toolbar button labels can easily be set and customized using underlying Java components. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/button-customization" rel="bookmark" title="Button customization">Button customization </a> <small>Matlab's button uicontrols (pushbutton and togglebutton) are basically wrappers for a Java Swing JButton object. This post describes how the buttons can be customized using this Java object in ways that are impossible using pure Matlab....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/hgs-undocumented-parameters-interface" rel="bookmark" title="HG&#039;s undocumented parameters interface">HG&#039;s undocumented parameters interface </a> <small>Some HG functions also accept inputs parameters in a struct fields rather than the normal P-V pairs format. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/undocumented-button-highlighting/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
