<?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>UI controls &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/category/ui-controls/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Tue, 29 Oct 2019 15:27:59 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
	<item>
		<title>Matlab toolstrip – part 6 (complex controls)</title>
		<link>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-toolstrip-part-6-complex-controls</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Mon, 21 Jan 2019 16:00:38 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8235</guid>

					<description><![CDATA[<p>Multiple types of customizable controls can be added to Matlab toolstrips</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls">Matlab toolstrip – part 6 (complex controls)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls" rel="bookmark" title="Matlab toolstrip – part 7 (selection controls)">Matlab toolstrip – part 7 (selection controls) </a> <small>Matlab toolstrips can contain a wide variety of selection controls: popups, combo-boxes, and galleries. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization" rel="bookmark" title="Matlab toolstrip – part 4 (control customization)">Matlab toolstrip – part 4 (control customization) </a> <small>Matlab toolstrip components (controls) can be customized in various ways, including user-defined callbacks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization" rel="bookmark" title="Matlab toolstrip – part 3 (basic customization)">Matlab toolstrip – part 3 (basic customization) </a> <small>Matlab toolstrips can be created and customized in a variety of ways. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In <a href="https://undocumentedmatlab.com/articles/tag/toolstrip" target="_blank">previous posts</a> I showed how we can create custom Matlab app toolstrips using simple controls such as buttons and checkboxes. Today I will show how we can incorporate more complex controls into our toolstrip: button groups, edit-boxes, spinners, sliders etc.<br />
<center><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_Controls.png" alt="Some custom Toolstrip Controls" title="Some custom Toolstrip Controls" width="80%" style="max-width:727px;"/></center><br />
Toolstrips can be a bit complex to develop so I’m proceeding slowly, with each post in the miniseries building on the previous posts. I encourage you to review the earlier posts in the <a href="https://undocumentedmatlab.com/articles/tag/toolstrip" target="_blank">Toolstrip miniseries</a> before reading this post.<br />
<span id="more-8235"></span><br />
The first place to search for potential toostrip components/controls is in <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1" target="_blank">Matlab&#8217;s built-in toolstrip demos</a>. The <code>showcaseToolGroup</code> demo displays a large selection of generic components grouped by function. These controls&#8217; callbacks do little less than simply output a text message in the Matlab console. On the other hand, the <code>showcaseMPCDesigner</code> demo shows a working demo with controls that interact with some docked figures and their plot axes. The combination of these demos should provide plenty of ideas for your own toolstrip implementation. Their m-file source code is available in the <i>%matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+desktop/</i> folder. To see the available toolstrip controls in action and how they could be integrated, refer to the source-code of these two demos.<br />
All toolstrip controls are defined by classes in the <i>%matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+toolstrip/</i> folder and use the <code>matlab.ui.internal.toolstrip</code> package prefix, for example:</p>
<pre lang="matlab">
% Alternative 1:
hButton = matlab.ui.internal.toolstrip.Button;
% Alternative 2:
import matlab.ui.internal.toolstrip.*
hButton = Button;
</pre>
<p>For the remainder of today&#8217;s post it is assumed that you are using one of these two alternatives whenever you access any of the toolstrip classes.</p>
<h3 id="controls">Top-level toolstrip controls</h3>
<table>
<tbody>
<tr>
<th>Control</th>
<th>Description</th>
<th>Important properties</th>
<th>Callbacks</th>
<th>Events</th>
</tr>
<tr>
<td><code>EmptyControl</code></td>
<td>Placeholder (filler) in container column</td>
<td>(none)</td>
<td>(none)</td>
<td>(none)</td>
</tr>
<tr>
<td><code>Label</code></td>
<td>Simple text label (no action)</td>
<td><b>Icon</b>, <b>Text</b> (string)</td>
<td>(none)</td>
<td>(none)</td>
</tr>
<tr>
<td><code>Button</code></td>
<td>Push-button</td>
<td><b>Icon</b>, <b>Text</b> (string)</td>
<td><b>ButtonPushedFcn</b></td>
<td>ButtonPushed</td>
</tr>
<tr>
<td><code>ToggleButton</code></td>
<td>Toggle (on/off) button</td>
<td><b>Icon</b>, <b>Text</b> (string), <b>Value</b> (logical true/false), <b>ButtonGroup</b> (a <code>ButtonGroup</code> object)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged</td>
</tr>
<tr>
<td><code>RadioButton</code></td>
<td>Radio-button (on/off)</td>
<td><b>Text</b> (string), <b>Value</b> (logical true/false), <b>ButtonGroup</b> (a <code>ButtonGroup</code> object)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged</td>
</tr>
<tr>
<td><code>CheckBox</code></td>
<td>Check-box (on/off)</td>
<td><b>Text</b> (string), <b>Value</b> (logical true/false)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged</td>
</tr>
<tr>
<td><code>EditField</code></td>
<td>Single-line editbox</td>
<td><b>Value</b> (string)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged, FocusGained, FocusLost</td>
</tr>
<tr>
<td><code>TextArea</code></td>
<td>Multi-line editbox</td>
<td><b>Value</b> (string)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged, FocusGained, FocusLost</td>
</tr>
<tr>
<td><code>Spinner</code></td>
<td>A numerical spinner control of values between min,max</td>
<td><b>Limits</b> ([min,max]), <b>StepSize</b> (integer), <b>NumberFormat</b> (&#8216;integer&#8217; or &#8216;double&#8217;), <b>DecimalFormat</b> (string), <b>Value</b> (numeric)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged, ValueChanging</td>
</tr>
<tr>
<td><code>Slider</code></td>
<td>A horizontal slider of values between min,max</td>
<td><b>Limits</b> ([min,max]), <b>Labels</b> (cell-array), <b>Ticks</b> (integer), <b>UseSmallFont</b> (logical true/false, R2018b onward), <b>ShowButton</b> (logical true/false, undocumented), <b>Steps</b> (integer, undocumented), <b>Value</b> (numeric)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged, ValueChanging</td>
</tr>
<tr>
<td><code>ListBox</code></td>
<td>List-box selector with multiple items</td>
<td><b>Items</b> (cell-array), <b>SelectedIndex</b> (integer), <b>MultiSelect</b> (logical true/false), <b>Value</b> (cell-array of strings)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged</td>
</tr>
<tr>
<td><code>DropDown</code></td>
<td>Single-selection drop-down (combo-box) selector</td>
<td><b>Items</b> (cell-array), <b>SelectedIndex</b> (integer), <b>Editable</b> (logical true/false), <b>Value</b> (string)</td>
<td><b>ValueChangedFcn</b></td>
<td>ValueChanged</td>
</tr>
<tr>
<td><code>DropDownButton</code></td>
<td>Button that has an associated drop-down selector</td>
<td><b>Icon</b>, <b>Text</b> (string), <b>Popup</b> (a <code>PopupList</code> object)</td>
<td><b>DynamicPopupFcn</b></td>
<td>(none)</td>
</tr>
<tr>
<td><code>SplitButton</code></td>
<td>Split button: main clickable part next to a drop-down selector</td>
<td><b>Icon</b>, <b>Text</b> (string), <b>Popup</b> (a <code>PopupList</code> object)</td>
<td><b>ButtonPushedFcn</b>, <b>DynamicPopupFcn</b></td>
<td>ButtonPushed, DropDownPerformed (undocumented)</td>
</tr>
<tr>
<td><code>Gallery</code></td>
<td>A gallery of selectable options, displayed in-panel</td>
<td><b>MinColumnCount</b> (integer), <b>MaxColumnCount</b> (integer), <b>Popup</b> (a <code>GalleryPopup</code> object), <b>TextOverlay</b> (string)</td>
<td>(none)</td>
<td>(none)</td>
</tr>
<tr>
<td><code>DropDownGalleryButton</code></td>
<td>A gallery of selectable options, displayed as a drop-down</td>
<td><b>MinColumnCount</b> (integer), <b>MaxColumnCount</b> (integer), <b>Popup</b> (a <code>GalleryPopup</code> object), <b>TextOverlay</b> (string)</td>
<td>(none)</td>
<td>(none)</td>
</tr>
</tbody>
</table>
<p>In addition to the control properties listed in the table above, all toolstrip controls share some common properties:</p>
<ul>
<li><b>Description</b> &#8211; a string that is shown in a tooltip when you hover the mouse over the control</li>
<li><b>Enabled</b> &#8211; a logical value (default: true) that controls whether we can interact with the control. A disabled control is typically grayed-over. Note that the value is a logical true/false, not &#8216;on&#8217;/&#8217;off&#8217;</li>
<li><b>Tag</b> &#8211; a string that can be used to uniquely identify/locate the control via their container&#8217;s <i>find(tag)</i> and <i>findAll(tag)</i> methods. Can contain spaces and special symbols &#8211; does not need to be a valid Matlab identifier</li>
<li><b>Children</b> &#8211; contains a list of sub-component (if any); useful with complex controls</li>
<li><b>Parent</b> &#8211; the handle of the container that contains the control</li>
<li><b>Type</b> &#8211; the type of control, typically its class-name</li>
<li><b>Mnemonic</b> &#8211; an undocumented string property, currently unused (?)</li>
<li><b>Shortcut</b> &#8211; an undocumented string property, currently unused (?)</li>
</ul>
<p>The <code>EmptyControl</code>, <code>Button</code>, <code>ToggleButton</code> and <code>CheckBox</code> controls were discussed in an <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization#example" target="_blank">earlier post</a> of this miniseries. The bottom 6 selection controls (<code>ListBox</code>, <code>DropDown</code>, <code>DropDownButton</code>, <code>SplitButton</code>, <code>Gallery</code> and <code>DropDownGalleryButton</code>) will be discussed in the next post. The rest of the controls are described below.</p>
<h3 id="ButtonGroup">Button groups</h3>
<p>A ButtonGroup binds several <code>CheckBox</code> and <code>ToggleButton</code> components such that only one of them is selected (pressed) at any point in time. For example:</p>
<pre lang="matlab">
hSection = hTab.addSection('Radio-buttons');
hColumn = hSection.addColumn();
% Grouped RadioButton controls
hButtonGroup = ButtonGroup;
hRadio = RadioButton(hButtonGroup, 'Option choice #1');
hRadio.ValueChangedFcn = @ValueChangedCallback;
hColumn.add(hRadio);
hRadio = RadioButton(hButtonGroup, 'Option choice #2');
hRadio.ValueChangedFcn = @ValueChangedCallback;
hRadio.Value = true;
hColumn.add(hRadio);
</pre>
<p><center><figure style="width: 119px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_RadioButton.png" alt="Toolstrip ButtonGroup" title="Toolstrip ButtonGroup" width="119" height="82" /><figcaption class="wp-caption-text">Toolstrip ButtonGroup</figcaption></figure></center> Note that unlike the <i><b>uibuttongroup</b></i> object in &#8220;standard&#8221; figure GUI, the toolstrip&#8217;s <code>ButtonGroup</code> object does not have a SelectionChangedFcn callback property (or corresponding event). Instead, we need to set the <b>ValueChangedFcn</b> callback property (or listen to the ValueChanged event) separately for each individual control. This is really a shame &#8211; I think it would make good design sense to have a SelectionChangedFcn callback at the <code>ButtonGroup</code> level, as we do for <i><b>uibuttongroup</b></i> (in addition to the individual control callbacks).<br />
Also note that the internal documentation of <code>ButtonGroup</code> has an error &#8211; it provides an example usage with <code>RadioButton</code> that has its constructor inputs switched: the correct constructor is <code>RadioButton(hButtonGroup,labelStr)</code>. On the other hand, for <code>ToggleButton</code>, the hButtonGroup input is the [optional] 3rd input arg of the constructor: <code>ToggleButton(labelStr,Icon,hButtonGroup)</code>. I think that it would make much more sense for the <code>RadioButton</code> constructor to follow the documentation and the style of <code>ToggleButton</code> and make the hButtonGroup input the last (2nd, optional) input arg, rather than the 1st. In other words, it would make more sense for RadioButton(labelStr,hButtonGroup), but unfortunately this is currently not the case.</p>
<h3 id="Edit">Label, EditField and TextArea</h3>
<p>A <code>Label</code> control is a simple non-clickable text label with an optional <b>Icon</b>, whose text is controlled via the <b>Text</b> property. The label&#8217;s alignment is controlled by the containing column&#8217;s <b>HorizontalAlignment</b> property.<br />
An <code>EditField</code> is a single-line edit-box. Its string contents can be fetched/updated via the <b>Value</b> property, and when the user updates the edit-box contents the <b>ValueChangedFcn</b> callback is invoked (upon each modification of the string, i.e. every key-click). This is a pretty simple control actually.<br />
The <code>EditField</code> control has a hidden (undocumentented) settable property called <b>PlaceholderText</b>, which presumably aught to display a gray initial prompt within the editbox. However, as far as I could see this property has no effect (perhaps, as the name implies, it is a place-holder for a future functionality&#8230;).<br />
A <code>TextArea</code> is another edit-box control, but enables entering multiple lines of text, unlike <code>EditField</code> which is a single-line edit-box. <code>TextArea</code> too is a very simple control, having a settable <b>Value</b> string property and a <b>ValueChangedFcn</b> callback. Whereas <code>EditField</code> controls, being single-line, would typically be included in 2- or 3-element toolstrip columns, the <code>TextArea</code> would typically be placed in a single-element column, so that it would span the entire column height.<br />
A peculiarity of toolstrip columns is that unless you specify their <b>Width</b> property, the internal controls are displayed with a minimal width (the width is only controllable at the column level, not the control-level). This is especially important with <code>EditField</code> and <code>TextArea</code> controls, which are often empty by default, causing their assigned width to be minimal (only a few pixels). This is corrected by setting their containing column&#8217;s <b>Width</b>:</p>
<pre lang="matlab">
% EditField controls
column1 = hSection.addColumn('HorizontalAlignment','right');
column1.add(Label('Yaba:'))
column1.add(Label('Daba doo:'))
column2 = hSection.addColumn('Width',70);
column2.add(EditField);
column2.add(EditField('Initial text'));
% TextArea control
column3 = hSection.addColumn('Width',90);
hEdit = TextArea;
hEdit.ValueChangedFcn = @ValueChangedCallback;
column3.add(hEdit);
</pre>
<p><center><figure style="width: 233px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_Editboxes.png" alt="Toolstrip Label, EditField and TextArea" title="Toolstrip Label, EditField and TextArea" width="233" height="100" /><figcaption class="wp-caption-text">Toolstrip Label, EditField and TextArea</figcaption></figure></center></p>
<h3 id="Spinner">Spinner</h3>
<p><code>Spinner</code> is a single-line numeric editbox that has an attached side-widget where you can increase/decrease the editbox value by a specified amount, subject to predefined min/max values. If you try to enter an illegal value, Matlab will beep and the editbox will revert to its last acceptable value. You can only specify a <b>NumberFormat</b> of &#8216;integer&#8217; or &#8216;double&#8217; (default: &#8216;integer&#8217;) and a <b>DecimalFormat</b> which is a string composed of the number of sub-decimal digits to display and the format (&#8216;e&#8217; or &#8216;f&#8217;). For example, <b>DecimalFormat</b>=&#8217;4f&#8217; will display 4 digits after the decimal in floating-point format (&#8216;e&#8217; means engineering format). Here is a short usage example (notice the different ways that we can set the callbacks):</p>
<pre lang="matlab">
hColumn = hSection.addColumn('Width',100);
% Integer spinner (-100 : 10 : 100)
hSpinner = Spinner([-100 100], 0);  % [min,max], initialValue
hSpinner.Description = 'this is a tooltip description';
hSpinner.StepSize = 10;
hSpinner.ValueChangedFcn = @ValueChangedCallback;
hColumn.add(hSpinner);
% Floating-point spinner (-10 : 0.0001 : 10)
hSpinner = Spinner([-10 10], pi);  % [min,max], initialValue
hSpinner.NumberFormat = 'double';
hSpinner.DecimalFormat = '4f';
hSpinner.StepSize = 1e-4;
addlistener(hSpinner,'ValueChanged', @ValueChangedCallback);
addlistener(hSpinner,'ValueChanging',@ValueChangingCallback);
hColumn.add(hSpinner);
</pre>
<p><center><figure style="width: 110px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_Spinner.png" alt="Toolstrip Spinner" title="Toolstrip Spinner" width="110" height="95" /><figcaption class="wp-caption-text">Toolstrip Spinner</figcaption></figure></center> A logical extension of the toolstrip spinner implementation would be for <a href="https://undocumentedmatlab.com/articles/using-spinners-in-matlab-gui" target="_blank">non-numeric spinners</a>, as well as custom <b>Value</b> display formatting. Perhaps this will become available at some future Matlab release.</p>
<h3 id="Slider">Slider</h3>
<p><code>Slider</code> is a horizontal ruler on which you can move a knob from the left (min <b>Value</b>) to the right (max <b>Value</b>). The ticks and labels are optional and customizable. Here is a simple example showing a plain slider (values between 0-100, initial value 70, ticks every 5, labels every 20, step size 1), followed by a custom slider (notice again the different ways that we can set the callbacks):</p>
<pre lang="matlab">
hColumn = hSection.addColumn('Width',200);
hSlider = Slider([0 100], 70);  % [min,max], initialValue
hSlider.Description = 'this is a tooltip';
tickVals = 0 : 20 : 100;
hSlider.Labels = [compose('%d',tickVals); num2cell(tickVals)]';  % {'0',0; '20',20; ...}
hSlider.Ticks = 21;  % =numel(0:5:100)
hSlider.ValueChangedFcn = @ValueChangedCallback;
hColumn.add(hSlider);
hSlider = Slider([0 100], 40);  % [min,max], initialValue
hSlider.Labels = {'Stop' 0; 'Slow' 20; 'Fast' 50; 'Too fast' 75; 'Crash!' 100};
try hSlider.UseSmallFont = true; catch, end  % UseSmallFont was only added in R2018b
hSlider.Ticks = 11;  % =numel(0:10:100)
addlistener(hSlider,'ValueChanged', @ValueChangedCallback);
addlistener(hSlider,'ValueChanging',@ValueChangingCallback);
hColumn.add(hSlider);
</pre>
<p><center><figure style="width: 217px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_Slider.png" alt="Toolstrip Slider" title="Toolstrip Slider" width="217" height="95" /><figcaption class="wp-caption-text">Toolstrip Slider</figcaption></figure></center></p>
<h3 id="roadmap">Toolstrip miniseries roadmap</h3>
<p>The next post will discuss complex selection components, including listbox, drop-down, split-button, and gallery.<br />
Following that, I plan to discuss toolstrip collapsibility, the ToolPack framework, docking layout, DataBrowser panel, QAB (Quick Access Bar), underlying Java controls, and adding toolstrips to figures &#8211; not necessarily in this order.<br />
Matlab toolstrips can be a bit complex, so I plan to proceed in small steps, each post building on top of its predecessors.<br />
If you would like me to assist you in building a custom toolstrip or GUI for your Matlab program, <a href="https://undocumentedmatlab.com/consulting" target="_blank">please let me know</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls">Matlab toolstrip – part 6 (complex controls)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-7-selection-controls" rel="bookmark" title="Matlab toolstrip – part 7 (selection controls)">Matlab toolstrip – part 7 (selection controls) </a> <small>Matlab toolstrips can contain a wide variety of selection controls: popups, combo-boxes, and galleries. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization" rel="bookmark" title="Matlab toolstrip – part 4 (control customization)">Matlab toolstrip – part 4 (control customization) </a> <small>Matlab toolstrip components (controls) can be customized in various ways, including user-defined callbacks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization" rel="bookmark" title="Matlab toolstrip – part 3 (basic customization)">Matlab toolstrip – part 3 (basic customization) </a> <small>Matlab toolstrips can be created and customized in a variety of ways. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-6-complex-controls/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Matlab toolstrip – part 4 (control customization)</title>
		<link>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-toolstrip-part-4-control-customization</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 30 Dec 2018 16:00:00 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8110</guid>

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

					<description><![CDATA[<p>A built-in JIDE control can be used in Matlab GUI for IP-address entry/display. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/ip-address-input-control">IP address input control</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/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/ishghandle-undocumented-input-parameter" rel="bookmark" title="ishghandle&#039;s undocumented input parameter">ishghandle&#039;s undocumented input parameter </a> <small>The built-in function ishghandle accepts a second input argument with the expected handle type....</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>
<li><a href="https://undocumentedmatlab.com/articles/jide-property-grids" rel="bookmark" title="JIDE Property Grids">JIDE Property Grids </a> <small>The JIDE components pre-bundled in Matlab enable creating user-customized property grid tables...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A few weeks ago, a user posted <a href="https://www.mathworks.com/matlabcentral/answers/375588-get-ip-address-over-a-edit-box" rel="nofollow" target="_blank">a question on Matlab Answers</a>, asking whether it is possible to implement a text input control that accepts and validates an IP address (for example, &#8216;192.168.1.101&#8217;). While doing this using purely documented Matlab code is indeed possible (for those of us who are masochistically inclined and/or have nothing else to do with their spare time), a very simple-to-use and polished-looking solution is to use an undocumented built-in Matlab control.<br />
The solution is based on the fact that Matlab comes with a huge set of professional Java-based controls by JideSoft, bundled in various JAR libraries within the <i>%matlabroot%/java/jarext/jide</i> Matlab installation folder. For our specific purposes (an IP-address entry/display control), we are interested in the <code>com.jidesoft.field.IPTextField</code> control (<a href="http://www.jidesoft.com/javadoc/com/jidesoft/field/IPTextField.html" rel="nofollow" target="_blank">online documentation</a>), which is part of the JIDE Grids library (<i>%matlabroot%/java/jarext/jide/jide-grids.jar</i>). We can use it as follows:</p>
<pre lang="matlab">
jIPField = com.jidesoft.field.IPTextField('255.255.255.0');  % set default IP
[jIPField, hContainer] = javacomponent(jIPField, [10,10,120,20], hParent);  % hParent: panel/figure handle
</pre>
<p><center><figure style="width: 193px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/IPTextField.png" alt="IPTextField control in a Matlab GUI" title="IPTextField control in a Matlab GUI" width="193" height="84" /><figcaption class="wp-caption-text">IPTextField control in a Matlab GUI</figcaption></figure></center><br />
You can modify the position/size of the text-field in the <i><b>javacomponent</b></i> call above, or by modifying the <b>Position</b> / <b>Units</b> properties of the returned <code>hContainer</code>.<br />
We can retrieve the IP text/numeric values using:</p>
<pre lang="matlab">
vals = jIPField.getValue';         % 1x4 uint32 array => [255,255,255,0]
vals = cell(jIPField.getRawText)'; % 1x4 string cells => {'255','255','255','0'}
ip   = char(jIPField.getText);     % entire IP string => '255.255.255.0'
</pre>
<p>The <code>IPTextField</code> component auto-validates the IP values, ensuring that the displayed IP is always valid (for example, IP components cannot be negative or larger than 255). The component has many other features, including the ability to enable/disable, color or format the IP components etc.<br />
<span id="more-7313"></span><br />
We can set a callback function to process user changes, by setting the component&#8217;s *StateChangedCallback* property, for example:</p>
<pre lang="matlab">jIPField.StateChangedCallback = @(jComponent,jEventData) disp(jComponent.getValue');</pre>
<p>The JIDE libraries that come with Matlab contain numerous other similarly-useful components, including <a href="/articles/using-jide-combo-boxes" target="_blank">date/time/font/color/file/folder selectors</a>, <a href="/articles/date-selection-components" target="_blank">calendars in various formats</a>, credit-card fields, and many more.<br />
For more information about using the <a href="/articles/javacomponent" target="_blank"><i><b>javacomponent</b></i> function</a> and handling Java components in Matlab GUI, see other posts on this website &#8211; particularly those marked with the <a href="/articles/tag/jide" target="_blank">&#8220;JIDE&#8221; tag</a>.<br />
Additional discussion of JIDE&#8217;s combo-boxes, and JIDE controls in general, is available in Chapter 5 of my <a target="_blank" href="/books/matlab-java">Matlab-Java Programming book</a>.<br />
If you need to integrate professional-looking controls such as these in your Matlab GUI, consider hiring my <a target="_blank" href="/consulting/">consulting services</a>.</p>
<h3 id="Caution">Caution</h3>
<p>Remember that JIDE evolves with Matlab, and so JIDE’s online documentation, which refers to the latest JIDE version, may be partially inapplicable if you use an old Matlab version. In any case, Matlab releases always lag the latest JIDE release by at least a year (e.g., Matlab R2017b still uses JIDE v3.4.1 that was released in June 2012 &#8211; MathWorks used to update the bundled JIDE libraries to newer versions, but for some reason has stopped doing that in 2013). The older your Matlab, the more such inconsistencies that you may find. For example, I believe that <code>DateSpinnerComboBox</code> only became available around R2010b; similarly, some control properties behave differently (or are missing altogether) in different releases. To determine the version of JIDE that you are currently using in Matlab, run the following (the result can then be compared to JIDE&#8217;s official <a target="_blank" rel="nofollow" href="http://www.jidesoft.com/history/">change-log history</a>):</p>
<pre lang='matlab'>
>> com.jidesoft.utils.Lm.getProductVersion
ans =
3.4.1
</pre>
<p>Note that JIDE is a commercial product. We may not use it without JIDESoft&#8217;s permission outside the Matlab environment. It is my understanding however, that we can freely use it within Matlab. Note that this is not legal advise as I am an engineer, not a lawyer. If you have any licensing questions, contact sales@jidesoft.com.<br />
Also note that all of JIDE&#8217;s controls use the Java-based figures (that are created using GUIDE or the <i><b>figure</b></i> function), and will not work on the new web-based uifigures (created using App Designer or the <i><b>uifigure</b></i> function). There is currently no corresponding IP entry/display control for web-based GUIs, and since there is [still] no way to integrate external Javascript/CSS libraries in uifigures, the only resort is to use a plain-vanilla edit-box. If MathWorks would simply open a hook to integrate external JS/CSS libraries, that would enable users to use 3rd-party libraries that have such custom controls and MathWorks would then not need to spend a huge amount of effort to develop multiple UI control variants.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/ip-address-input-control">IP address input control</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/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/ishghandle-undocumented-input-parameter" rel="bookmark" title="ishghandle&#039;s undocumented input parameter">ishghandle&#039;s undocumented input parameter </a> <small>The built-in function ishghandle accepts a second input argument with the expected handle type....</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>
<li><a href="https://undocumentedmatlab.com/articles/jide-property-grids" rel="bookmark" title="JIDE Property Grids">JIDE Property Grids </a> <small>The JIDE components pre-bundled in Matlab enable creating user-customized property grid tables...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/ip-address-input-control/feed</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing uifigures part 3</title>
		<link>https://undocumentedmatlab.com/articles/customizing-uifigures-part-3?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-uifigures-part-3</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-uifigures-part-3#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Mon, 27 Nov 2017 15:00:24 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[AppDesigner]]></category>
		<category><![CDATA[Iliya Romm]]></category>
		<category><![CDATA[uifigure]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7169</guid>

					<description><![CDATA[<p>As I have repeatedly posted in recent years, Matlab is advancing towards web-based GUI. The basic underlying technology is more-or-less stable: an HTML/Javascript webpage that is created-on-the-fly and rendered in a stripped-down browser window (based on Chromium-based jxBrowser in recent years). However, the exact mechanism by which the controls (&#8220;widgets&#8221;) are actually converted into visible [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-uifigures-part-3">Customizing uifigures part 3</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-uifigures-part-2" rel="bookmark" title="Customizing uifigures part 2">Customizing uifigures part 2 </a> <small>Matlab's new web-based uifigures can be customized using custom CSS and Javascript code. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-uifigures-part-1" rel="bookmark" title="Customizing uifigures part 1">Customizing uifigures part 1 </a> <small>Matlab's new web-based uifigures can be customized in a variety of undocumented ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-web-gui-uipanel" rel="bookmark" title="Customizing web-GUI uipanel">Customizing web-GUI uipanel </a> <small>We can customize Matlab's new web-based GUI panels in many interesting ways. Here's how... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-uifigure-javascript-events" rel="bookmark" title="Matlab callbacks for uifigure JavaScript events">Matlab callbacks for uifigure JavaScript events </a> <small>Matlab callback code can be attached to JavaScript events in web-based uifigures. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>As I have repeatedly posted in recent years, Matlab is advancing towards web-based GUI. The basic underlying technology is more-or-less stable: an HTML/Javascript webpage that is created-on-the-fly and rendered in a stripped-down browser window (based on Chromium-based <a href="https://www.teamdev.com/jxbrowser" rel="nofollow" target="_blank">jxBrowser</a> in recent years). However, the exact mechanism by which the controls (&#8220;widgets&#8221;) are actually converted into visible components (currently based on the <a href="https://dojotoolkit.org" rel="nofollow" target="_blank">Dojo toolkit</a> and its Dijit UI library) and interact with Matlab (i.e., the internal Matlab class structures that interact with the browser and Dojo) is still undergoing changes and is not quite as stable.<br />
Customization hacks reported on this blog last year (<a href="/articles/customizing-uifigures-part-1" target="_blank">part 1</a>, <a href="/articles/customizing-uifigures-part-2" target="_blank">part 2</a>) may fail in some cases due to the changing nature of the undocumented internals. Some examples are the way by which we can extract the uifigure&#8217;s URL (which <a href="/articles/customizing-uifigures-part-2#comment-407215" target="_blank">changed in R2017a</a>), the ability to display and debug uifigures in a standard webbrowser with associated dev tools (which seems to have stopped working in R2017b), and the way by which we can extract the Dijit reference of displayed uicontrols.<br />
Greatly assisting in this respect is Iliya Romm, who was the guest blogger for <a href="/articles/customizing-uifigures-part-2" target="_blank">part 2</a> of this series last year. Iliya co-authored the open-source (GitHub) <a href="https://github.com/StackOverflowMATLABchat/mlapptools" rel="nofollow" target="_blank">mlapptools toolbox</a>, which enables accessing and customizing uifigure components using standard CSS, without users having to bother about the ugly hacks discussed in the previous parts of the series. This toolbox is really just a single Matlab class (<code>mlapptools</code>), contained within a single m-file (<i>mlapptools.m</i>). In addition to this class, the toolbox includes a <i>README.md</i> mark-down usage documentation, and two demo functions, <i>DOMdemoGUI.m</i> and <i>TableDemo.m</i>.<br />
Here is the effect of using <i>TableDemo</i>, that shows how we can customize individual uitable cells (each uitable cell is a separate Dijit widget that can be customized individually):<br />
<center><figure style="width: 363px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="CSS customizations of uifigure components" src="https://undocumentedmatlab.com/images/uifigure_uitable_colors.png" title="CSS customizations of uifigure components" width="363" height="188" /><figcaption class="wp-caption-text">CSS customizations of uifigure components</figcaption></figure></center><br />
<span id="more-7169"></span><br />
The <i>mlapptools</i> class contains several static methods that can be used individually:</p>
<ul>
<li><i><b>textAlign</b>(uielement, alignment)</i> &#8211; Modify text horizontal alignment (<code>'left'</code>, <code>'center'</code>, <code>'right'</code>, <code>'justify'</code> or <code>'initial'</code>)</li>
<li><i><b>fontWeight</b>(uielement, weight)</i> &#8211; Modify font weight (<code>'normal'</code>, <code>'bold'</code>, <code>'bolder'</code>, <code>'lighter'</code> or <code>'initial'</code>), depending on availability in the font-face used</li>
<li><i><b>fontColor</b>(uielement, color)</i> &#8211; Modify font color (e.g. <code>'red'</code>, <code>'#ff0000'</code>, <code>'rgb(255,0,0)'</code> or <a href="https://www.w3.org/TR/css3-color/" rel="nofollow" target="_blank">other variants</a>)</li>
<li><i><b>setStyle</b>(uielement, styleAttr, styleValue)</i> &#8211; Modify a specified <a href="https://www.w3schools.com/cssref/" rel="nofollow" target="_blank">CSS style</a> attribute</li>
<li><i><b>aboutDojo</b>()</i> &#8211; Return version information about the Dojo toolkit</li>
<li><i><b>getHTML</b>(hFig)</i> &#8211; Return the full HTML code of a uifigure</li>
<li><i><b>getWebWindow</b>(hFig)</i> &#8211; Return a webwindow handle from a uifigure handle</li>
<li><i><b>getWebElements </b>(hControl)</i> &#8211; Return a webwindow handle and a widget ID for the specified uicontrol handle</li>
<li><i><b>getWidgetList</b>(hFig, verboseFlag)</i> &#8211; Return a cell-array of structs containing information about all widgets in the uifigure</li>
<li><i><b>getWidgetInfo</b>(hWebwindow, widgetId, verboseFlag)</i> &#8211; Return information about a specific dijit widget</li>
<li><i><b>setTimeout</b>(hFig, seconds)</i> &#8211; Override the default timeout (=5 secs) for dojo commands, for a specific uifigure</li>
</ul>
<p>A few simple usage examples:</p>
<pre lang="matlab">
mlapptools.fontColor(hButton,'red')  % set red text color
mlapptools.fontWeight(hButton,'bold')  % set bold text font
mlapptools.setStyle(hButton,'border','2px solid blue')  % add a 2-pixel solid blue border
mlapptools.setStyle(hButton,'background-image','url(https://www.mathworks.com/etc/designs/mathworks/img/pic-header-mathworks-logo.svg)')  % add background image
</pre>
<p>Once you download <i>mlapptools</i> and add its location to the Matlab path, you can use it in any web-based GUI that you create, either programmatically or with Add-Designer.<br />
The <i>mlapptools</i> is quite well written and documented, so if you are interested in the inner workings I urge you to take a look at this class&#8217;s private methods. For example, to understand how a Matlab uicontrol handle is converted into a Dojo widget-id, which is then used with the built-in <i>dojo.style()</i> Javascript function to modify the CSS attributes of the HTML <code>&lt;div&gt;</code> or <code>&lt;span&gt;</code> that are the control&#8217;s visual representation on the webpage. An explanation of the underlying mechanism can be found in <a href="/articles/customizing-uifigures-part-2" target="_blank">part 2</a> of this series of articles on uifigure customizations. Note that the <i>mlapptools</i> code is newer than the article and contains some new concepts that were not covered in that article, for example searching through Dijit&#8217;s registry of displayed widgets.<br />
<b>Note</b>: web-based GUI is often referred to as &#8220;App-Designed&#8221; (AD) GUI, because using the Matlab App Designer is the typical way to create and customize such GUIs. However, just as great-looking GUIs could be created programmatically rather than with GUIDE, so too can web-based GUIS be created programmatically, using regular built-in Matlab commands such as <i><b>uifigure</b></i>, <i><b>uibutton</b></i> and <i><b>uitable</b></i> (an example of such programmatic GUI creation can be found in Iliya&#8217;s <i>TableDemo.m</i>, discussed above). For this reason, I believe that the new GUIs should be referred to as &#8220;uifigures&#8221; or &#8220;web GUIs&#8221;, and not as &#8220;AD GUIs&#8221;.<br />
If you have any feature requests or bugs related to <i>mlapptools</i>, please report them on its <a href="https://github.com/StackOverflowMATLABchat/mlapptools/issues" rel="nofollow" target="_blank">GitHub issues page</a>. For anything else, please add a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-uifigures-part-3">Customizing uifigures part 3</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-uifigures-part-2" rel="bookmark" title="Customizing uifigures part 2">Customizing uifigures part 2 </a> <small>Matlab's new web-based uifigures can be customized using custom CSS and Javascript code. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-uifigures-part-1" rel="bookmark" title="Customizing uifigures part 1">Customizing uifigures part 1 </a> <small>Matlab's new web-based uifigures can be customized in a variety of undocumented ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-web-gui-uipanel" rel="bookmark" title="Customizing web-GUI uipanel">Customizing web-GUI uipanel </a> <small>We can customize Matlab's new web-based GUI panels in many interesting ways. Here's how... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-uifigure-javascript-events" rel="bookmark" title="Matlab callbacks for uifigure JavaScript events">Matlab callbacks for uifigure JavaScript events </a> <small>Matlab callback code can be attached to JavaScript events in web-based uifigures. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-uifigures-part-3/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>GUI formatting using HTML</title>
		<link>https://undocumentedmatlab.com/articles/gui-formatting-using-html?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=gui-formatting-using-html</link>
					<comments>https://undocumentedmatlab.com/articles/gui-formatting-using-html#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 05 Apr 2017 20:26:44 +0000</pubDate>
				<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[uifigure]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6877</guid>

					<description><![CDATA[<p>HTML formatting an be used to align and background-color text  within Matlab uicontrols such as buttons, listboxes, uitables etc. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/gui-formatting-using-html">GUI formatting using HTML</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/sending-html-emails-from-matlab" rel="bookmark" title="Sending HTML emails from Matlab">Sending HTML emails from Matlab </a> <small>Matlab's sendmail only sends simple text messages by default; a simple hack can cause it to send HTML-formatted messages. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/html-support-in-matlab-uicomponents" rel="bookmark" title="HTML support in Matlab uicomponents">HTML support in Matlab uicomponents </a> <small>Matlab uicomponents support HTML and CSS, enabling colored items, superscript/subscript, fonts, bold/italic/underline and many other modifications...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/gui-integrated-html-panel" rel="bookmark" title="GUI integrated HTML panel">GUI integrated HTML panel </a> <small>Simple HTML can be presented in a Java component integrated in Matlab GUI, without requiring the heavy browser control....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/formatting-numbers" rel="bookmark" title="Formatting numbers">Formatting numbers </a> <small>Number formatting is easy to achieve in Matlab, by using a dedicated built-in Java object....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>As I&#8217;ve mentioned several times in the past, <a href="/articles/html-support-in-matlab-uicomponents" target="_blank">HTML can be used for simple formatting of GUI controls</a>, including font colors/sizes/faces/angles. With a bit of thought, HTML (and some CSS) can also be used for non-trivial formatting, that would otherwise require the <a href="/articles/button-customization" target="_blank">use of Java</a>, such as text alignment, background color, and using a combination of text and icons in the GUI control&#8217;s contents.</p>
<h3 id="Alignment">Alignment</h3>
<p>For example, a question that I am often asked (<a href="/articles/html-support-in-matlab-uicomponents#comment-403579" target="_blank">latest example</a>) is whether it is possible to left/center/right align the label within a Matlab button, listbox or table. While Matlab does not (yet) have properties that control alignment in uicontrols, we can indeed use HTML for this. There&#8217;s a catch though: if we simply tried to use <code>&lt;div align="left"&gt;</code>&#8230;, it will not work. No error will be generated but we will not see any visible left-alignment. The reason is that internally, the text is contained within a snugly-fitting box. Aligning anything within a tight-fitting box obviously has no effect.<br />
To solve the problem, we need to tell Matlab (or rather, the HTML interpreter used by the underlying Java control) to widen this internal box. One way to do this is to specify the width of the <code>div</code> tag, which can be enormous in order to span the entire available apace (<code>&lt;div width="999px" align="left"&gt;</code>&#8230;). Another method is to simulate a simple HTML table that contains a single cell that holds the text, and then tell HTML the table cell&#8217;s width:</p>
<pre lang="matlab">
hButton.String   = '<html><tr><td width=9999 align=left>Left-aligned';  % left-align within a button
hTable.Data{2,1} = '<html><tr><td width=9999 align=right>And right';   % right-align within a specific uitable cell
</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 />
<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 />
I discussed the specific aspect of uicontrol content alignment in <a href="/articles/aligning-uicontrol-contents" target="_blank">another post</a> last year.</p>
<h3 id="bgcolor">Background color</h3>
<p>The same problem (and solution) applies to background colors: if we don&#8217;t enlarge the snugly-fitting internal bounding-box, any HTML bgcolor that we specify would only be shown under the text (i.e., within the internal box&#8217;s confines). In order to display bgcolor across the entire control/cell width, we need to enlarge the internal box&#8217;s width (the <code>align</code> and <code>bgcolor</code> tags can of course be used together):<br />
<span id="more-6877"></span></p>
<pre lang="matlab">
hButton.String   = '<html><tr><td width=9999 bgcolor=#ffff00>Yellow';  % bgcolor within a button
hTable.Data{2,1} = '<html><tr><td width=9999 bgcolor=#ffff00>Yellow';  % bgcolor within a specific uitable cell
</pre>
<h3 id="CSS">CSS</h3>
<p>We can also use simple CSS, which provides more formatting customizability than plain HTML:</p>
<pre lang="matlab">
hTable.Data{2,1} = '<html><tr><td width=9999 style="background-color:yellow">Yellow';
</pre>
<p>HTML/CSS formatting is a poor-man&#8217;s hack. It is very crude compared to the numerous customization options available via Java. However, it does provide a reasonable solution for many use-cases, without requiring any Java. I discussed the two approaches for uitable cell formatting <a href="/articles/uitable-cell-colors" target="_blank">in this post</a>.</p>
<h3 id="uifigures">[Non-]support in uifigures</h3>
<p><b><u>Important note</u></b>: HTML formatting  is <b>NOT</b> [yet] supported by the new web-based uifigures. While uifigures can indeed be hacked with HTML/CSS content (<a href="/articles/uitable-cell-colors" target="_blank">details</a>), this is not an easy task. Since it should be trivially easy for MathWorks to enable HTML content in the new web-based uifigures, I implore anyone who uses HTML in their Matlab GUI to let MathWorks know about it so that they could prioritize this R&#038;D effort into an upcoming Matlab release. You can send an email to Eric.Sargent at mathworks.com, who apparently handles such aspects in MathWorks&#8217; R&#038;D efforts to transition from Java-based GUIs to web-based ones. In my previous post I spotlit MathWorks <a href="/articles/mathworks-solicited-java-survey" target="_blank">user-feedback surveys</a> about users&#8217; use of Java GUI aspects, aimed in order to migrate as many of the use-cases as possible onto the new web-based framework. HTML/CSS support is a natural by-product of the fact that Matlab&#8217;s non-web-based GUI is based on Java Swing components (that inherently support HTML/CSS). But unfortunately the MathWorks surveys are specific to the <i><b>javacomponent</b></i> function and the figure&#8217;s <b>JavaFrame</b> property. In other words, many users might be using undocumented Java aspects by simply using HTML content in their GUI, without ever realizing it or using <i><b>javacomponent</b></i>. So I think that in this case a simple email to Eric.Sargent at mathworks.com to let him know how you&#8217;re using HTML would be more useful. Maybe one day MathWorks will be kind enough to post a similar survey specific to HTML support, or maybe one day they&#8217;s just add the missing HTML support, if only to be done with my endless nagging. 🙂<br />
p.s. &#8211; I am well aware that we can align and bgcolor buttons in AppDesigner. But we can&#8217;t do this with individual table/listbox cells, and in general we can&#8217;t use HTML within uifigures without extensive hacks. I merely used the simple examples of button and uitable cell formatting in today&#8217;s post to illustrate the issue. So please don&#8217;t get hung up on the specifics, but rather on the broader issue of HTML support in uifigures.<br />
And in the meantime, for as long as non-web-based GUI is still supported in Matlab, keep on enjoying the benefits that HTML/CSS provides.</p>
<h3 id="email">Automated bug-fix emails</h3>
<p>In an unrelated matter, I wish to express my Kudos to the nameless MathWorkers behind the scenes who, bit by bit, improve Matlab and the user experience: Over the years I&#8217;ve posted a few times <a href="/articles/couple-of-matlab-bugs-and-workarounds" target="_blank">my frustrations</a> with the opaqueness of MathWorks&#8217; bug-reporting mechanism. One of my complaints was that users who file bugs are not notified when a fix or workaround becomes available. That at least seems to have been fixed now. I just received a seemingly-automated email notifying me that one of the bugs that I reported a few years ago has been fixed. This is certainly a good step in the right direction, so thank you!<br />
Happy Passover/Easter to all!</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/gui-formatting-using-html">GUI formatting using HTML</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/sending-html-emails-from-matlab" rel="bookmark" title="Sending HTML emails from Matlab">Sending HTML emails from Matlab </a> <small>Matlab's sendmail only sends simple text messages by default; a simple hack can cause it to send HTML-formatted messages. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/html-support-in-matlab-uicomponents" rel="bookmark" title="HTML support in Matlab uicomponents">HTML support in Matlab uicomponents </a> <small>Matlab uicomponents support HTML and CSS, enabling colored items, superscript/subscript, fonts, bold/italic/underline and many other modifications...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/gui-integrated-html-panel" rel="bookmark" title="GUI integrated HTML panel">GUI integrated HTML panel </a> <small>Simple HTML can be presented in a Java component integrated in Matlab GUI, without requiring the heavy browser control....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/formatting-numbers" rel="bookmark" title="Formatting numbers">Formatting numbers </a> <small>Number formatting is easy to achieve in Matlab, by using a dedicated built-in Java object....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/gui-formatting-using-html/feed</wfw:commentRss>
			<slash:comments>6</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 loading="lazy" 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>Faster findjobj</title>
		<link>https://undocumentedmatlab.com/articles/faster-findjobj?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=faster-findjobj</link>
					<comments>https://undocumentedmatlab.com/articles/faster-findjobj#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Mon, 11 Apr 2016 09:18:14 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[FindJObj]]></category>
		<category><![CDATA[JavaFrame]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented property]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6376</guid>

					<description><![CDATA[<p>the ubiquitous findjobj utility has been significantly improved for speed for the most common use case. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/faster-findjobj">Faster findjobj</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/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/findjobj-gui-display-container-hierarchy" rel="bookmark" title="FindJObj GUI &#8211; display container hierarchy">FindJObj GUI &#8211; display container hierarchy </a> <small>The FindJObj utility can be used to present a GUI that displays a Matlab container's internal Java components, properties and callbacks....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/faster-csvwrite-dlmwrite" rel="bookmark" title="Faster csvwrite/dlmwrite">Faster csvwrite/dlmwrite </a> <small>The speed of the builtin csvwrite, dlmwrite functions can be improved dramatically. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/additional-uicontrol-tooltip-hacks" rel="bookmark" title="Additional uicontrol tooltip hacks">Additional uicontrol tooltip hacks </a> <small>Matlab's uicontrol tooltips have several limitations that can be overcome using the control's underlying Java object....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>My <a href="/articles/findjobj-find-underlying-java-object" target="_blank"><i><b>findjobj</b></i> utility</a>, created in 2007 and updated over the years, has received wide recognition and is employed by numerous Matlab programs, including a few dozen utilities in the Matlab File Exchange. I am quite proud of this utility and find it extremely useful for customizing Matlab controls in many ways that are impossible using standard Matlab properties. I have shown <a href="/?s=findjobj" target="_blank">many examples of this</a> in this blog over the past years.<br />
I am happy to announce that I have just uploaded a new version of <i><b>findjobj</b></i> to the <a href="http://www.mathworks.com/matlabcentral/fileexchange/14317-findjobj-find-java-handles-of-matlab-graphic-objects" rel="nofollow" target="_blank">Matlab File Exchange</a>, which significantly improves the utility&#8217;s performance for the most common use-case of a single input and a single output, namely finding the handle of the underlying Java component (peer) of a certain Matlab control:</p>
<pre lang="matlab">
>> hButton = uicontrol('String','click me!');
>> tic, jButton = findjobj(hButton); toc  % old findjobj
Elapsed time is 1.513217 seconds.
>> tic, jButton = findjobj(hButton); toc  % new findjobj
Elapsed time is 0.029348 seconds.
</pre>
<p>The new <i><b>findjobj</b></i> is backward-compatible with the old <i><b>findjobj</b></i> and with all prior Matlab releases. It is a drop-in replacement that will significantly improve your program&#8217;s speed.<br />
The new version relies on several techniques:<span id="more-6376"></span><br />
First, as I <a href="/articles/customizing-matlab-uipanels" rel="nofollow" target="_blank">showed last year</a>, in HG2 (R2014 onward), Matlab <i><b>uipanel</b></i>s have finally become full-featured Java <code>JPanel</code>s, that can be accessed and customized in many interesting manners. More to the point here, we can now directly access the underlying <code>JPanel</code> component handle using the <i><b>uipanel</b></i>&#8216;s hidden <b>JavaFrame</b> property (thanks to MathWorks for supplying this useful hook!). The new <i><b>findjobj</b></i> version detects this and immediately returns this handle if the user specified a <i><b>uipanel</b></i> input.<br />
I still do not know of any direct way to retrieve the underlying Java component&#8217;s handle for Matlab <i><b>uicontrol</b></i>s, this has been a major frustration of mine for quite a few years. So, we need to find the containing Java container in which we will recursively search for the control&#8217;s underlying Java handle. In the old version of <i><b>finjobj</b></i>, we retrieve the containing figure&#8217;s <code>JFrame</code> reference and from it the <code>ContentPane</code> handle, and use this handle as the Java container that is recursively searched. This is quite slow when the figure window is heavily-laden with multiple controls. In the new version, we try to use the specified Matlab <i><b>uicontrol</b></i>&#8216;s direct parent, which is very often a <i><b>uipanel</b></i>. In this case, we can directly retrieve the panel&#8217;s <code>JPanel</code> reference as explained above. This results in a must smaller and faster search since we need to recursively search far fewer controls within the container, compared to the figure&#8217;s <code>ContentPane</code>.<br />
In addition, I used a <a href="/articles/findjobj-gui-display-container-hierarchy#comment-332487" target="_blank">suggestion</a> by blog reader Hannes for a faster recursive search that uses the control&#8217;s tooltip rather than its size, position and class. Finally, the search order is reversed to search backward from the last child component, since this is the component that will most often contain the requested control peer.<br />
Feel free to download and use the new <i><b>findjobj</b></i> version. The code for the fast variant can be found in lines #190-205 and #3375-3415.<br />
Enjoy!<br />
p.s. &#8211; as I explained last week, today&#8217;s discussion, and in general anything that has to do with Java peers of GUI controls, only relates to the existing <code>JFrame</code>-based figure windows, not to the new web-based <i><b>uifigure</b></i>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/faster-findjobj">Faster findjobj</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/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/findjobj-gui-display-container-hierarchy" rel="bookmark" title="FindJObj GUI &#8211; display container hierarchy">FindJObj GUI &#8211; display container hierarchy </a> <small>The FindJObj utility can be used to present a GUI that displays a Matlab container's internal Java components, properties and callbacks....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/faster-csvwrite-dlmwrite" rel="bookmark" title="Faster csvwrite/dlmwrite">Faster csvwrite/dlmwrite </a> <small>The speed of the builtin csvwrite, dlmwrite functions can be improved dramatically. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/additional-uicontrol-tooltip-hacks" rel="bookmark" title="Additional uicontrol tooltip hacks">Additional uicontrol tooltip hacks </a> <small>Matlab's uicontrol tooltips have several limitations that can be overcome using the control's underlying Java object....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/faster-findjobj/feed</wfw:commentRss>
			<slash:comments>11</slash:comments>
		
		
			</item>
	</channel>
</rss>
