<?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>Internal component &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/internal-component/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 05 Feb 2020 08:57:49 +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>Undocumented plot marker types</title>
		<link>https://undocumentedmatlab.com/articles/undocumented-plot-marker-types?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=undocumented-plot-marker-types</link>
					<comments>https://undocumentedmatlab.com/articles/undocumented-plot-marker-types#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 13 Mar 2019 11:05:14 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8539</guid>

					<description><![CDATA[<p>Undocumented plot marker styles can easily be accesses using a hidden plot-line property. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-plot-marker-types">Undocumented plot marker types</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/types-of-undocumented-matlab-aspects" rel="bookmark" title="Types of undocumented Matlab aspects">Types of undocumented Matlab aspects </a> <small>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-behavior" rel="bookmark" title="Undocumented scatter plot behavior">Undocumented scatter plot behavior </a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" rel="bookmark" title="Plot markers transparency and color gradient">Plot markers transparency and color gradient </a> <small>Matlab plot-line markers can be customized to have transparency and color gradients. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-jitter" rel="bookmark" title="Undocumented scatter plot jitter">Undocumented scatter plot jitter </a> <small>Matlab's scatter plot can automatically jitter data to enable better visualization of distribution density. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>I wanted to take a break from my miniseries on the Matlab toolstrip to describe a nice little undocumented aspect of plot line markers. Plot line marker types have remained essentially unchanged in user-facing functionality for the past two+ decades, allowing the well-known marker types (.,+,o,^ etc.). Internally, lots of things changed in the graphics engine, particularly in the <a href="https://undocumentedmatlab.com/articles/hg2-update" target="_blank">transition to HG2</a> in R2014b and the <a href="https://blogs.mathworks.com/graphics/2015/11/10/memory-consumption/#comment-465" rel="nofollow" target="_blank">implementation of markers using OpenGL primitives</a>. I suspect that during the massive amount of development work that was done at that time, important functionality improvements that were implemented in the engine were forgotten and did not percolate all the way up to the user-facing functions. I highlighted a few of these in the past, for example transparency and color gradient for <a href="https://undocumentedmatlab.com/articles/plot-line-transparency-and-color-gradient" target="_blank">plot lines</a> and <a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" target="_blank">markers</a>, or <a href="https://undocumentedmatlab.com/articles/hidden-hg2-plot-functionality" target="_blank">various aspects of contour plots</a>.<br />
Fortunately, Matlab usually exposes the internal objects that we can customize and which enable these extra features, in hidden properties of the top-level graphics handle. For example, the standard Matlab plot-line handle has a hidden property called <b>MarkerHandle</b> that we can access. This returns an internal object that enables <a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" target="_blank">marker transparency and color gradients</a>. We can also use this object to set the marker style to a couple of formats that are not available in the top-level object:</p>
<pre lang="matlab">
>> x=1:10; y=10*x; hLine=plot(x,y,'o-'); box off; drawnow;
>> hLine.MarkerEdgeColor = 'r';
>> set(hLine, 'Marker')'  % top-level marker styles
ans =
  1×14 cell array
    {'+'} {'o'} {'*'} {'.'} {'x'} {'square'} {'diamond'} {'v'} {'^'} {'>'} {'<'} {'pentagram'} {'hexagram'} {'none'}
>> set(hLine.MarkerHandle, 'Style')'  % low-level marker styles
ans =
  1×16 cell array
    {'plus'} {'circle'} {'asterisk'} {'point'} {'x'} {'square'} {'diamond'} {'downtriangle'} {'triangle'} {'righttriangle'} {'lefttriangle'} {'pentagram'} {'hexagram'} {'vbar'} {'hbar'} {'none'}
</pre>
<p>We see that the top-level marker styles directly correspond to the low-level styles, except for the low-level &#8216;vbar&#8217; and &#8216;hbar&#8217; styles. Perhaps the developers forgot to add these two styles to the top-level object in the enormous upheaval of HG2. Luckily, we can set the hbar/vbar styles directly, using the line&#8217;s <b>MarkerHandle</b> property:</p>
<pre lang="matlab">
hLine.MarkerHandle.Style = 'hbar';
set(hLine.MarkerHandle, 'Style','hbar');  % alternative
</pre>
<p><center><figure style="width: 213px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/plot_hbar.png" alt="hLine.MarkerHandle.Style='hbar'" title="hLine.MarkerHandle.Style='hbar'" width="213" height="155" /><figcaption class="wp-caption-text">hLine.MarkerHandle.Style='hbar'</figcaption></figure> <figure style="width: 213px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/plot_vbar.png" alt="hLine.MarkerHandle.Style='vbar'" title="hLine.MarkerHandle.Style='vbar'" width="213" height="155" /><figcaption class="wp-caption-text">hLine.MarkerHandle.Style='vbar'</figcaption></figure></center></p>
<h3 id="USA">USA visit</h3>
<p>I will be travelling in the US in May/June 2019. Please let me know (altmany at gmail) if you would like to schedule a meeting or onsite visit for consulting/training, or perhaps just to explore the possibility of my professional assistance to your Matlab programming needs.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-plot-marker-types">Undocumented plot marker types</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/types-of-undocumented-matlab-aspects" rel="bookmark" title="Types of undocumented Matlab aspects">Types of undocumented Matlab aspects </a> <small>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-behavior" rel="bookmark" title="Undocumented scatter plot behavior">Undocumented scatter plot behavior </a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" rel="bookmark" title="Plot markers transparency and color gradient">Plot markers transparency and color gradient </a> <small>Matlab plot-line markers can be customized to have transparency and color gradients. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-jitter" rel="bookmark" title="Undocumented scatter plot jitter">Undocumented scatter plot jitter </a> <small>Matlab's scatter plot can automatically jitter data to enable better visualization of distribution density. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/undocumented-plot-marker-types/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Sliders in Matlab GUI &#8211; part 2</title>
		<link>https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sliders-in-matlab-gui-part-2</link>
					<comments>https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 05 Jul 2018 11:40:56 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7728</guid>

					<description><![CDATA[<p>Matlab contains a variety of ways to define/display slider controls in GUI windows. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2">Sliders in Matlab GUI &#8211; part 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/sliders-in-matlab-gui" rel="bookmark" title="Sliders in Matlab GUI">Sliders in Matlab GUI </a> <small>Professional-looking slider controls can easily be integrated in Matlab GUI. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uiundo-matlab-undocumented-undo-redo-manager" rel="bookmark" title="uiundo &#8211; Matlab&#039;s undocumented undo/redo manager">uiundo &#8211; Matlab&#039;s undocumented undo/redo manager </a> <small>The built-in uiundo function provides easy yet undocumented access to Matlab's powerful undo/redo functionality. This article explains its usage....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-and-the-event-dispatch-thread-edt" rel="bookmark" title="Matlab and the Event Dispatch Thread (EDT)">Matlab and the Event Dispatch Thread (EDT) </a> <small>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/blurred-matlab-figure-window" rel="bookmark" title="Blurred Matlab figure window">Blurred Matlab figure window </a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Exactly 3 years ago I posted about various <a href="/articles/sliders-in-matlab-gui" target="_blank">alternatives for embedding sliders in Matlab GUI</a>. Today I will follow up on that post with a description of yet another undocumented builtin alternative &#8211; <i><b>controllib.widget.Slider</b></i>. A summary of the various alternatives can be seen in the following screenshot:<br />
<center><figure style="width: 344px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" src="https://undocumentedmatlab.com/images/sliders.gif" alt="Slider alternatives in Matlab GUI" title="Slider alternatives in Matlab GUI" width="344" height="303" /><figcaption class="wp-caption-text">Slider alternatives in Matlab GUI</figcaption></figure></center><br />
The <i><b>controllib.widget.Slider</b></i> component is a class in Matlab&#8217;s internal <code>controllib</code> package (last week I discussed a different utility function in this package, <a href="/articles/string-char-compatibility" target="_blank"><i><b>controllib.internal.util.hString2Char</b></i></a>).<br />
<span id="more-7728"></span><br />
<i><b>controllib.widget.Slider</b></i> accepts 3 input arguments: containing figure handle, position in pixels, and data values. For example:</p>
<pre lang="matlab">
>> hSlider = controllib.widget.Slider(gcf, [10,10,100,50], 5:25)
hSlider =
  Slider with properties:
        Data: [6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25]
       Index: 11
       Value: 15
    FontSize: 8
    Position: [10 10 100 50]
</pre>
<p>This creates an invisible axes at the specified figure location and displays graphic axes objects that provide the appearance of the slider. When you move the slider&#8217;s knob, or click its centerline or arrows (&#8220;Steppers&#8221;), the slider&#8217;s value changes accordingly.<br />
You can attach a callback function to the slider as follows:</p>
<pre lang="matlab">
myCallback = @(h,e) disp(h.Value);  % as an example
addlistener(hSlider, 'ValueChanged', myCallback);
</pre>
<p>Note that <i><b>controllib.widget.Slider</b></i> is based on pure-Matlab code and fully-supported functionality. The Matlab source code is available (<i>%matlabroot%/toolbox/shared/controllib/graphics/+controllib/+widget/Slider.m</i>) and quite readable. So while it does not actually work with the new web-based uifigures, is should be relatively easy to adapt the code so that this component could be displayed in such uifigures.<br />
Below is a script to recreate the screenshot above. Note the two alternative mechanisms for setting properties (Java setter-method notation, and HG set notation):</p>
<pre lang="matlab">
hFig = figure('Color','w');

% 1. controllib.widget.Slider
hSlider1 = controllib.widget.Slider(hFig, [10,10,100,50], 1:20);
hSlider1.Value = 12;

% 2. uicontrol
hSlider2 = uicontrol('style','slider', 'units','pixels', 'pos',[10,80,100,20], 'Min',0', 'Max',20, 'Value',12);

% 3. JScrollBar
jSlider3 = javaObjectEDT(javax.swing.JScrollBar);
jSlider3.setOrientation(jSlider3.HORIZONTAL);  % Java setter-method notation
set(jSlider3, 'VisibleAmount',1, 'Minimum',0, 'Maximum',20, 'Value',12);  % HG set notation
[hSlider3, hContainer3] = javacomponent(jSlider3, [10,130,100,20], hFig);

% 4. JSlider #1
jSlider4 = javaObjectEDT(javax.swing.JSlider(0,20,12))
jSlider4.setBackground(java.awt.Color.white);  % Java setter-method notation
set(jSlider4, 'MinorTickSpacing',1, 'MajorTickSpacing',4, 'SnapToTicks',true, 'PaintLabels',true);  % HG set notation
[hSlider4, hContainer4] = javacomponent(jSlider4, [10,180,100,30], hFig);

% 5. JSlider #2
jSlider5 = javaObjectEDT(javax.swing.JSlider(0,20,12))
jSlider5.setBackground(java.awt.Color.white);  % Java setter-method notation
jSlider5.setPaintTicks(true);
set(jSlider5, 'MinorTickSpacing',1, 'MajorTickSpacing',4, 'SnapToTicks',true, 'PaintLabels',true);  % HG set notation
[hSlider5, hContainer5] = javacomponent(jSlider5, [10,230,100,40], hFig);
</pre>
<p>For additional details regarding the other slider alternatives, please refer to <a href="/articles/sliders-in-matlab-gui" target="_blank">my earlier post</a> on this subject.<br />
Have you ever used another interesting utility or class in Matlab&#8217;s builtin packages? If so, please tell us about it in a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2">Sliders in Matlab GUI &#8211; part 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/sliders-in-matlab-gui" rel="bookmark" title="Sliders in Matlab GUI">Sliders in Matlab GUI </a> <small>Professional-looking slider controls can easily be integrated in Matlab GUI. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uiundo-matlab-undocumented-undo-redo-manager" rel="bookmark" title="uiundo &#8211; Matlab&#039;s undocumented undo/redo manager">uiundo &#8211; Matlab&#039;s undocumented undo/redo manager </a> <small>The built-in uiundo function provides easy yet undocumented access to Matlab's powerful undo/redo functionality. This article explains its usage....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-and-the-event-dispatch-thread-edt" rel="bookmark" title="Matlab and the Event Dispatch Thread (EDT)">Matlab and the Event Dispatch Thread (EDT) </a> <small>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/blurred-matlab-figure-window" rel="bookmark" title="Blurred Matlab figure window">Blurred Matlab figure window </a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/sliders-in-matlab-gui-part-2/feed</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
		<item>
		<title>Builtin PopupPanel widget</title>
		<link>https://undocumentedmatlab.com/articles/builtin-popuppanel-widget?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=builtin-popuppanel-widget</link>
					<comments>https://undocumentedmatlab.com/articles/builtin-popuppanel-widget#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 06 Dec 2017 16:00:34 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[Internal component]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7188</guid>

					<description><![CDATA[<p>We can use a built-in Matlab popup-panel widget control to display lightweight popups that are attached to a figure window.  </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/builtin-popuppanel-widget">Builtin PopupPanel widget</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/auto-completion-widget" rel="bookmark" title="Auto-completion widget">Auto-completion widget </a> <small>Matlab includes a variety of undocumented internal controls that can be used for an auto-completion component. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-2" rel="bookmark" title="Speeding-up builtin Matlab functions &#8211; part 2">Speeding-up builtin Matlab functions &#8211; part 2 </a> <small>Built-in Matlab functions can often be profiled and optimized for improved run-time performance. This article shows a typical example. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-1" rel="bookmark" title="Speeding-up builtin Matlab functions &#8211; part 1">Speeding-up builtin Matlab functions &#8211; part 1 </a> <small>Built-in Matlab functions can often be profiled and optimized for improved run-time performance. This article shows a typical example. ...</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>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>8 years ago I blogged about Matlab&#8217;s builtin <a href="/articles/customizing-help-popup-contents" target="_blank">HelpPopup widget</a>. This control is used by Matlab to display popup-windows with help documentation, but can also be used by users to display custom lightweight popups that contain HTML-capable text and even URLs of entire webpages. Today I&#8217;d like to highlight another builtin Matlab widget, <code>ctrluis.PopupPanel</code>, which can be used to display rich contents in a lightweight popup box attached to a specific Matlab figure:<br />
<center><figure style="width: 425px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Matlab's builtin PopupPanel widget" src="https://undocumentedmatlab.com/images/PopupPanel_animated.gif" title="Matlab's builtin PopupPanel widget" width="425" height="386" /><figcaption class="wp-caption-text">Matlab's builtin PopupPanel widget</figcaption></figure></center><br />
As you can see, this popup-panel displays richly-formatted contents, having either an opaque or transparent background, with vertical scrollbars being applied automatically. The popup pane is not limited to displaying text messages &#8211; in fact, it can display any Java GUI container (e.g. a settings panel). This popup-panel is similar in concept to the HelpPopup widget, and yet much more powerful in several aspects.<br />
<span id="more-7188"></span></p>
<h3 id="create">Creating the popup panel</h3>
<p>Creating a <code>PopupPanel</code> is very simple:</p>
<pre lang="matlab">
% Create the popup-panel in the specified figure
hPopupPanel = ctrluis.PopupPanel(gcf);  % use gcf or any figure handle
hPopupPanel.setPosition([.1,.1,.8,.8]);  % set panel position (normalized units)
% Alternative #1: set popup-panel's contents to some HTML-formatted message
% note: createMessageTextPane() has optional input args FontName (arg #2), FontSize (#3)
jPanel = ctrluis.PopupPanel.createMessageTextPane('testing <b><i>123</i></b> ...')
hPopupPanel.setPanel(jPanel);
% Alternative #2: set popup-panel's contents to a webpage URL
url = 'https://undocumentedmatlab.com/files/sample-webpage.html';
jPanel = javaObjectEDT(javax.swing.JEditorPane(url));
hPopupPanel.setPanel(jPanel);
</pre>
<p>The entire contents are embedded within a scroll-box (which is a <code>com.mathworks.widgets.LightScrollPane</code> object) whose scrollbars automatically appear as-needed, so we don&#8217;t need to worry about the contents fitting the allocated space.<br />
To display custom GUI controls in the popup, we can simply contain those GUI controls in a Java container (e.g., a <code>JPanel</code>) and then do <code>hPopupPanel.setPanel(jPanel)</code>. This functionality can be used to create unobtrusive settings panels, input dialogs etc.<br />
The nice thing about the popup widget is that it is attached to the figure, and yet is not assigned a heavyweight window (so it does not appear in the OS task-bar). The popup moves along with the figure when the figure is moved, and is automatically disposed when the figure is closed.<br />
A few caveats about the <code>ctrluis.PopupPanel</code> control:</p>
<ul>
<li>The widget&#8217;s parent is expected to be a figure that has pixel units. If it doesn&#8217;t, the internal computations of <code>ctrluis.PopupPanel</code> croak.</li>
<li>The widget&#8217;s position is specified in normalized units (default: [0,0,1,1]). This normalized position is only used during widget creation: after creation, if you resize the figure the popup-panel&#8217;s position remains unchanged. To modify/update the position of the popup-panel programmatically, use <code>hPopupPanel.setPosition(newPosition)</code>. Alternatively, update the control&#8217;s Position property and then call <code>hPopupPanel.layout()</code> (there is no need to call <code>layout</code> when you use <code>setPosition</code>).</li>
<li>This functionality is only available for Java-based figures, not the new web-based (AppDesigner) uifigures.</li>
</ul>
<h3 id="customize">Popup panel customizations</h3>
<p>We can open/close the popup panel by clicking on its icon, as shown in the screenshots above, or programmatically using the control&#8217;s methods:</p>
<pre lang="matlab">
% Programmatically open/close the popup-panel
hPopupPanel.showPanel;
hPopupPanel.hidePanel;
% Show/hide entire popup-panel widget (including its icon)
hPopupPanel.setVisible(true);   % or .setVisible(1) or .Visible=1
hPopupPanel.setVisible(false);  % or .setVisible(0) or .Visible=0
</pre>
<p>To set a transparent background to the popup-panel (as shown in the screenshots above), we need to unset the opacity of the displayed panel and several of its direct parents:</p>
<pre lang="matlab">
% Set a transparent popup-panel background
for idx = 1 : 6
   jPanel.setOpaque(false);  % true=opaque, false=transparent
   jPanel = jPanel.getParent;
end
jPanel.repaint
</pre>
<p>Note that in the screenshots above, the panel&#8217;s background is made transparent, but the contained text and image remain opaque. Your displayed images can of course contain transparency and <a href="/articles/displaying-animated-gifs" target="_blank">animation</a>, if this is supported by the image format (for example, GIF).</p>
<h3 id="addMessagePane">iptui.internal.utilities.addMessagePane</h3>
<p><code>ctrluis.PopupPanel</code> is used internally by <code>iptui.internal.utilities.addMessagePane(hFig,message)</code> in order to display a minimizable single-line message panel at the top of a specified figure:</p>
<pre lang="matlab">hPopupPanel = iptui.internal.utilities.addMessagePane(gcf, 'testing <b>123</b> ...');  % note the HTML formatting</pre>
<p>The function updates the message panel&#8217;s position whenever the figure&#8217;s size is modified (by trapping the figure&#8217;s SizeChangedFcn), to ensure that the panel is always attached to the top of the figure and spans the full figure width. This is a simple function so I encourage you to take a look at its code (<i>%matlabroot%/toolbox/images/imuitools/+iptui/+internal/+utilities/addMessagePane.m</i>) &#8211; note that this might require the Image Processing Toolbox (I&#8217;m not sure).<br />
<center><figure style="width: 236px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Matlab's builtin iptui.internal.utilities.addMessagePane" src="https://undocumentedmatlab.com/images/PopupPanel5.png" title="Matlab's builtin iptui.internal.utilities.addMessagePane" width="236" height="202" /><figcaption class="wp-caption-text">Matlab's builtin iptui.internal.utilities.addMessagePane</figcaption></figure></center></p>
<h3 id="consulting">Professional assistance anyone?</h3>
<p>As shown by this and many other posts on this site, a polished interface and functionality is often composed of small professional touches, many of which are not exposed in the official Matlab documentation for various reasons. So if you need top-quality professional appearance/functionality in your Matlab program, or maybe just a Matlab program that is dependable, robust and highly-performant, consider employing my <a href="/consulting" target="_blank">consulting services</a>. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/builtin-popuppanel-widget">Builtin PopupPanel widget</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/auto-completion-widget" rel="bookmark" title="Auto-completion widget">Auto-completion widget </a> <small>Matlab includes a variety of undocumented internal controls that can be used for an auto-completion component. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-2" rel="bookmark" title="Speeding-up builtin Matlab functions &#8211; part 2">Speeding-up builtin Matlab functions &#8211; part 2 </a> <small>Built-in Matlab functions can often be profiled and optimized for improved run-time performance. This article shows a typical example. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-1" rel="bookmark" title="Speeding-up builtin Matlab functions &#8211; part 1">Speeding-up builtin Matlab functions &#8211; part 1 </a> <small>Built-in Matlab functions can often be profiled and optimized for improved run-time performance. This article shows a typical example. ...</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>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/builtin-popuppanel-widget/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Sending HTML emails from Matlab</title>
		<link>https://undocumentedmatlab.com/articles/sending-html-emails-from-matlab?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sending-html-emails-from-matlab</link>
					<comments>https://undocumentedmatlab.com/articles/sending-html-emails-from-matlab#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 02 Aug 2017 21:19:42 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Internal component]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6986</guid>

					<description><![CDATA[<p>Matlab's sendmail only sends simple text messages by default; a simple hack can cause it to send HTML-formatted messages. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/sending-html-emails-from-matlab">Sending HTML emails from Matlab</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-email-text-messages-from-matlab" rel="bookmark" title="Sending email/text messages from Matlab">Sending email/text messages from Matlab </a> <small>Sending emails and SMS (text) messages from Matlab is easy, once you know a few quirks....</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/gui-formatting-using-html" rel="bookmark" title="GUI formatting using HTML">GUI formatting using HTML </a> <small>HTML formatting an be used to align and background-color text within Matlab uicontrols such as buttons, listboxes, uitables etc. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A few months ago I wrote about various tricks for <a href="/articles/sending-email-text-messages-from-matlab" target="_blank">sending email/text messages from Matlab</a>. Unfortunately, Matlab only sends text emails by default and provides no documented way to send HTML-formatted emails. Text-only emails are naturally very bland and all mail clients in the past 2 decades support HTML-formatted emails. Today I will show how we can send such HTML emails from Matlab.<br />
A quick recap: Matlab&#8217;s <i><b>sendmail</b></i> function uses Java (specifically, the standard <code>javax.mail</code> package) to prepare and send emails. The Java classes are extremely powerful and so there is no wonder that Mathworks chose to use them rather than reinventing the wheel. However, Matlab&#8217;s <i><b>sendmail</b></i> function only uses part of the functionality exposed by these classes (admittedly, the most important parts that deal with the basic mail-sending mechanism), and does not expose external hooks or input args that would enable the user to take full advantage of the more advanced features, HTML formatting included.<br />
Only two small changes are needed in <i>sendmail.m</i> to support HTML formatting:</p>
<ol>
<li>HTML formatting required calling the message-object&#8217;s <i>setContent()</i> method, rather than <i>setText()</i>.</li>
<li>We need to specify <code>'text/html'</code> as part of the message&#8217;s encoding</li>
</ol>
<p><span id="more-6986"></span><br />
To implement these features, change the following (lines #119-130 in the original <i>sendmail.m</i> file of R2017a, changed lines highlighted):</p>
<pre lang="matlab" highlight="3-4,12">
% Construct the body of the message and attachments.
body = formatText(theMessage);
if numel(attachments) == 0
    if ~isempty(charset)
        msg.setText(body, charset);
    else
        msg.setText(body);
    end
else
    % Add body text.
    messageBodyPart = MimeBodyPart;
    if ~isempty(charset)
        messageBodyPart.setText(body, charset);
    ...
</pre>
<p>to this (changed lines highlighted):</p>
<pre lang="matlab" highlight="3-14,22-24">
% Construct the body of the message and attachments.
body = formatText(theMessage);
isHtml = ~isempty(body) && body(1) == '<';  % msg starting with '<' indicates HTML
if isHtml
    if isempty(charset)
        charset = 'text/html; charset=utf-8';
    else
        charset = ['text/html; charset=' charset];
    end
end
if numel(attachments) == 0  &#038;&#038; ~isHtml
    if isHtml
        msg.setContent(body, charset);
    elseif ~isempty(charset)
        msg.setText(body, charset);
    else
        msg.setText(body);
    end
    else
        % Add body text.
        messageBodyPart = MimeBodyPart;
        if isHtml
            messageBodyPart.setContent(body, charset);
        elseif ~isempty(charset)
            messageBodyPart.setText(body, charset);
        ...
</pre>
<p>In addition, I also found it useful to remove the hard-coded 75-character line-wrapping in text messages. This can be done by changing the following (line #291 in the original <i>sendmail.m</i> file of R2017a):</p>
<pre lang="matlab">maxLineLength = 75;</pre>
<p>to this:</p>
<pre lang="matlab">maxLineLength = inf;  % or some other large numeric value</pre>
<h3 id="deployment">Deployment</h3>
<p>It's useful to note two alternatives for making these fixes:</p>
<ul>
<li>Making the changes directly in <i>%matlabroot%/toolbox/matlab/iofun/sendmail.m</i>. You will need administrator rights to edit this file. You will also need to redo the fix whenever you install Matlab, either installation on a different machine, or installing a new Matlab release. In general, I discourage changing Matlab's internal files because it is simply not very maintainable.</li>
<li>Copying <i>%matlabroot%/toolbox/matlab/iofun/sendmail.m</i> into a dedicated wrapper function (e.g., <i>sendEmail.m</i>) that has a similar function signature and exists on the Matlab path. This has the benefit of working on multiple Matlab releases, and being copied along with the rest of our m-files when we install our Matlab program on a different computer. The downside is that our wrapper function will be stuck with the version of <i>sendmail.m</i> that we copied into it, and we'd lose any possible improvements that Mathworks may implement in future Matlab releases.</li>
</ul>
<p>The basic idea for the second alternative, the <i>sendEmail.m</i> wrapper, is something like this (the top highlighted lines are the additions made to the original <i>sendmail.m</i>, with everything placed in <i>sendEmail.m</i> on the Matlab path):<br />
<!--more--></p>
<pre lang="matlab" highlight="1-3">
function sendEmail(to,subject,theMessage,attachments)
%SENDEMAIL Send e-mail wrapper (with HTML formatting)
   sendmail(to,subject,theMessage,attachments);
% The rest of this file is copied from %matlabroot%/toolbox/matlab/iofun/sendmail.m (with the modifications mentioned above):
function sendmail(to,subject,theMessage,attachments)
%SENDMAIL Send e-mail.
%   SENDMAIL(TO,SUBJECT,MESSAGE,ATTACHMENTS) sends an e-mail.  TO is either a
%   character vector specifying a single address, or a cell array of character vector
...
</pre>
<p>We would then call the wrapper function as follows:</p>
<pre lang="matlab">
sendEmail('abc@gmail.com', 'email subject', 'regular text message');     % will send a regular text message
sendEmail('abc@gmail.com', 'email subject', '<b><font color="blue">HTML-formatted</font> <i>message');  % HTML-formatted message
</pre>
<p>In this case, the code automatically infers HTML formatting based on whether the first character in the message body is a '&lt;' character. Instead, we could just as easily have passed an additional input argument (<code>isHtml</code>) to our <i>sendEmail</i> wrapper function.<br />
Hopefully, in some future Matlab release Mathworks will be kind enough to enable sending 21<sup>st</sup>-century HTML-formatted emails without needing such hacks. Until then, note that <i>sendmail.m</i> relies on standard non-GUI Java networking classes, which are expected to be supported far into the future, well after Java-based GUI may cease to be supported in Matlab. For this reason I believe that while it seems a bit tricky, the changes that I outlined in today's post actually have a <a href="/articles/category/presumed-future-risk/low-risk-of-breaking-in-future-versions" target="_blank">low risk of breaking in a future Matlab release</a>.<br />
Do you have some other advanced email feature that you use in your Matlab program by some crafty customization to <i><b>sendmail</b></i>? If so, please share it in a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/sending-html-emails-from-matlab">Sending HTML emails from Matlab</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-email-text-messages-from-matlab" rel="bookmark" title="Sending email/text messages from Matlab">Sending email/text messages from Matlab </a> <small>Sending emails and SMS (text) messages from Matlab is easy, once you know a few quirks....</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/gui-formatting-using-html" rel="bookmark" title="GUI formatting using HTML">GUI formatting using HTML </a> <small>HTML formatting an be used to align and background-color text within Matlab uicontrols such as buttons, listboxes, uitables etc. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/sending-html-emails-from-matlab/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>uigetfile/uiputfile customizations</title>
		<link>https://undocumentedmatlab.com/articles/uigetfile-uiputfile-customizations?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=uigetfile-uiputfile-customizations</link>
					<comments>https://undocumentedmatlab.com/articles/uigetfile-uiputfile-customizations#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 02 Nov 2016 23:38:57 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Internal component]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6728</guid>

					<description><![CDATA[<p>A file-selector dialog window that includes an integrated preview panel is shown and explained. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/uigetfile-uiputfile-customizations">uigetfile/uiputfile customizations</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/figure-window-customizations" rel="bookmark" title="Figure window customizations">Figure window customizations </a> <small>Matlab figure windows can be customized in numerous manners using the underlying Java Frame reference. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uitab-customizations" rel="bookmark" title="Uitab customizations">Uitab customizations </a> <small>This article shows several customizations that can be done to Matlab's undocumented tab-panels functionality...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/figure-toolbar-customizations" rel="bookmark" title="Figure toolbar customizations">Figure toolbar customizations </a> <small>Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to customize the Matlab figure toolbar....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/bar-plot-customizations" rel="bookmark" title="Bar plot customizations">Bar plot customizations </a> <small>Matlab bar charts can be customized in various nifty ways. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab includes a few built-in file and folder selection dialog windows, namely <i><b>uigetfile</b></i>, <i><b>uiputfile</b></i> and <i><b>uigetdir</b></i>. Unfortunately, these functions are not easily extendable for user-defined functionalities. Over the years, several of my consulting clients have asked me to provide them with versions of these dialog functions that are customized in certain ways. In today&#8217;s post I discuss a few of these customizations: a file selector dialog with a preview panel, and automatic folder update as-you-type in the file-name edit box.<br />
It is often useful to have an integrated preview panel to display the contents of a file in a file-selection dialog. Clicking the various files in the tree-view would display a user-defined preview in the panel below, based on the file&#8217;s contents. An integrated panel avoids the need to manage multiple figure windows, one for the selector dialog and another for the preview. It also reduces the screen real-estate used by the dialog (also see the related <a href="#resizable">resizing customization</a> below).<br />
I call the end-result <i><b>uigetfile_with_preview</b></i>; you can <a href="https://www.mathworks.com/matlabcentral/fileexchange/60074-uigetfile-with-preview-gui-dialog-window-with-a-preview-panel" rel="nofollow" target="_blank">download it from the Matlab File Exchange</a>:</p>
<pre lang="matlab">filename = uigetfile_with_preview(filterSpec, prompt, folder, callbackFunction, multiSelectFlag)</pre>
<p><center><img decoding="async" alt="uigetfile_with_preview" src="https://undocumentedmatlab.com/images/uigetfile_with_preview.png" title="uigetfile_with_preview" width="75%" style="max-width:516px;" /></center><br />
<span id="more-6728"></span><br />
As you can see from the function signature, the user can specify the file-type filter, prompt and initial folder (quite similar to <i><b>uigetfile</b></i>, <i><b>uiputfile</b></i>), as well as a custom callback function for updating the preview of a selected file, and a flag to enable selecting multiple files (not just one).<br />
<i>uigetfile_with_preview.m</i> only has ~120 lines of code and plenty of comments, so feel free to download and review the code. It uses the following undocumented aspects:</p>
<ol>
<li>I used a <code>com.mathworks.hg.util.dFileChooser</code> component for the main file selector. This is a builtin Matlab control that extends the standard <code>javax.swing.JFileChooser</code> with a few properties and methods. I don&#8217;t really need the extra features, so you can safely replace the component with a <code>JFileChooser</code> if you wish (lines 54-55). Various properties of the file selector are then set, such as the folder that is initially displayed, the multi-selection flag, the <a href="/articles/javacomponent-background-color" target="_blank">component background color</a>, and the data-type filter options.</li>
<li>I used the <a href="/articles/javacomponent" target="_blank"><i><b>javacomponent</b></i> function</a> to place the file-selector component within the dialog window.</li>
<li>I set a callback on the component&#8217;s <b>PropertyChangeCallback</b> that is invoked whenever the user interactively selects a new file. This callback clears the preview panel and then calls the user-defined callback function (if available).</li>
<li>I set a callback on the component&#8217;s <b>ActionPerformedCallback</b> that is invoked whenever the user closes the figure or clicks the &#8220;Open&#8221; button. The selected filename(s) is/are then returned to the caller and the dialog window is closed.</li>
<li>I set a callback on the component&#8217;s file-name editbox&#8217;s <b>KeyTypedCallback</b> that is invoked whenever the user types in the file-name editbox. The callback checks whether the entered text looks like a valid folder path and if so then it automatically updates the displayed folder as-you-type.</li>
</ol>
<p>If you want to convert the code to a <i><b>uiputfile</b></i> variant, add the following code lines before the <i><b>uiwait</b></i> in line 111:</p>
<pre lang="matlab">
hjFileChooser.setShowOverwriteDialog(true);  % default: false (true will display a popup alert if you select an existing file)
hjFileChooser.setDialogType(hjFileChooser.java.SAVE_DIALOG);  % default: OPEN_DIALOG
hjFileChooser.setApproveButtonText('Save');  % or any other string. Default for SAVE_DIALOG: 'Save'
hjFileChooser.setApproveButtonToolTipText('Save file');  % or any other string. Default for SAVE_DIALOG: 'Save selected file'
</pre>
<p><i>In memory of my dear father.</i></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/uigetfile-uiputfile-customizations">uigetfile/uiputfile customizations</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/figure-window-customizations" rel="bookmark" title="Figure window customizations">Figure window customizations </a> <small>Matlab figure windows can be customized in numerous manners using the underlying Java Frame reference. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uitab-customizations" rel="bookmark" title="Uitab customizations">Uitab customizations </a> <small>This article shows several customizations that can be done to Matlab's undocumented tab-panels functionality...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/figure-toolbar-customizations" rel="bookmark" title="Figure toolbar customizations">Figure toolbar customizations </a> <small>Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to customize the Matlab figure toolbar....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/bar-plot-customizations" rel="bookmark" title="Bar plot customizations">Bar plot customizations </a> <small>Matlab bar charts can be customized in various nifty ways. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/uigetfile-uiputfile-customizations/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>MEX ctrl-c interrupt</title>
		<link>https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mex-ctrl-c-interrupt</link>
					<comments>https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 15 Jun 2016 17:00:40 +0000</pubDate>
				<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Pavel Holoborodko]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6454</guid>

					<description><![CDATA[<p>An undocumented MEX function can help interrupt running MEX functions. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt">MEX ctrl-c interrupt</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/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/undocumented-feature-list" rel="bookmark" title="Undocumented feature list">Undocumented feature list </a> <small>A list of undocumented MATLAB features can be retrieved. Here's how... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-matlab-mex-api" rel="bookmark" title="Undocumented Matlab MEX API">Undocumented Matlab MEX API </a> <small>Matlab's MEX API contains numerous undocumented functions, that can be extremely useful. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/serializing-deserializing-matlab-data" rel="bookmark" title="Serializing/deserializing Matlab data">Serializing/deserializing Matlab data </a> <small>Matlab does not provide a documented manner to serialize data into a byte stream, but we can do this with some undocumented functionality. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>I recently became aware of a <a href="http://www.caam.rice.edu/~wy1/links/mex_ctrl_c_trick/" rel="nofollow" target="_blank">very nice hack</a> by <a href="http://math.ucla.edu/~wotaoyin" rel="nofollow" target="_blank">Wotao Yin</a> (while at Rice in 2010; currently teaching at UCLA). The core problem is that unlike m-files that can be interrupted in mid-run using ctrl-c, MEX functions cannot be interrupted in the same way. Well, not officially, that is.<br />
Interrupts are very important for long-running user-facing operations. They can even benefit performance by avoiding the need to periodically poll some external state. Interrupts are registered asynchronously, and the program can query the interrupt buffer at its convenience, in special locations of its code, and/or at specific times depending on the required responsiveness.<br />
Yin reported that the <i>libut</i> library that ships with Matlab contain a large set of undocumented functions, including <code>utIsInterruptPending()</code> that can be used to detect ctrl-c interrupt events. The original report of this feature seems to be by Matlab old hand <a href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/37732#95811" rel="nofollow" target="_blank">Peter Boettcher back in 2002</a> (with a <a href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/326230" rel="nofollow" target="_blank">Fortran wrapper</a> reported in 2013). The importance of Yin&#8217;s post is that he clearly explained the use of this feature, with detailed coding and compilation instructions. Except for Peter&#8217;s original report, Yin&#8217;s post and the Fortran wrapper, precious few mentions can be found online (oddly enough, yours truly <a href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/247651#638201" rel="nofollow" target="_blank">mentioned it</a> in the very same CSSM newsletter post in which I outed this blog back in 2009). Apparently, this feature <a href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/37732" rel="nofollow" target="_blank">was supposed to have been made documented in R12.1</a>, but for some reason it was not and people just moved on and forgot about it.<br />
<span id="more-6454"></span><br />
The relevant functions seem to be:</p>
<pre lang="cpp">
// Most important functions (C):
bool utIsInterruptEnabled(void)
bool utIsInterruptPending(void)
bool utWasInterruptHandled(void)
bool utSetInterruptHandled(bool)
bool utSetInterruptEnabled(bool)
bool utSetInterruptPending(bool)
// Related functions (C, signature unknown):
? utHandlePendingInterrupt(?)
? utRestoreInterruptEnabled(?)
? utLongjmpIfInterruptPending(?)
// utInterruptMode class (C++):
utInterruptMode::utInterruptMode(enum utInterruptMode::Mode)  // constructor
utInterruptMode::~utInterruptMode(void)  // destructor
bool utInterruptMode::isInterruptEnabled(void)
enum utInterruptMode::Mode utInterruptMode::CurrentMode
enum utInterruptMode::Mode utInterruptMode::GetCurrentMode(void)
enum utInterruptMode::Mode utInterruptMode::GetOriginalMode(void)
enum utInterruptMode::Mode utInterruptMode::SetMode(enum utInterruptMode::Mode)
// utInterruptState class (C++):
class utInterruptState::AtomicPendingFlags utInterruptState::flags_pending
void utInterruptState::HandlePeekMsgPending(void)
bool utInterruptState::HandlePendingInterrupt(void)
bool utInterruptState::interrupt_handled
bool utInterruptState::IsInterruptPending(void)
bool utInterruptState::IsPauseMsgPending(void)
class utInterruptState & utInterruptState::operator=(class utInterruptState const &)
void utInterruptState::PeekMessageIfPending(void)
bool utInterruptState::SetInterruptHandled(bool)
bool utInterruptState::SetInterruptPending(bool)
bool utInterruptState::SetIqmInterruptPending(bool)
bool utInterruptState::SetPauseMsgPending(bool)
bool utInterruptState::SetPeekMsgPending(bool)
void utInterruptState::ThrowIfInterruptPending(void)
bool utInterruptState::WasInterruptHandled(void)
unsigned int const utInterruptState::FLAG_PENDING_CTRLC
unsigned int const utInterruptState::FLAG_PENDING_INTERRUPT_MASK
unsigned int const utInterruptState::FLAG_PENDING_IQM_INTERRUPT
unsigned int const utInterruptState::FLAG_PENDING_PAUSE
unsigned int const utInterruptState::FLAG_PENDING_PEEKMSG
</pre>
<p>Of all these functions, we can make do with just <code>utIsInterruptPending</code>, as <a href="http://www.caam.rice.edu/~wy1/links/mex_ctrl_c_trick/" rel="nofollow" target="_blank">shown</a> by Yin (complete with compilation instructions):</p>
<pre lang="cpp">
/* A demo of Ctrl-C detection in mex-file by Wotao Yin. Jan 29, 2010. */
#include "mex.h"
#if defined (_WIN32)
    #include <windows.h>
#elif defined (__linux__)
    #include <unistd.h>
#endif
#ifdef __cplusplus
    extern "C" bool utIsInterruptPending();
#else
    extern bool utIsInterruptPending();
#endif
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    int count = 0;
    while(1) {
        #if defined(_WIN32)
            Sleep(1000);        /* Sleep one second */
        #elif defined(__linux__)
            usleep(1000*1000);  /* Sleep one second */
        #endif
        mexPrintf("Count = %d\n", count++);  /* print count and increase it by 1 */
        mexEvalString("drawnow;");           /* flush screen output */
        if (utIsInterruptPending()) {        /* check for a Ctrl-C event */
            mexPrintf("Ctrl-C Detected. END\n\n");
            return;
        }
        if (count == 10) {
            mexPrintf("Count Reached 10. END\n\n");
            return;
        }
    }
}
</pre>
<p>After returning to Matlab, the Ctrl-C event will stop the execution of the caller function(s). However, sometimes we would like to keep the partial calculation, for example if the calculation can later be resumed from the point of interruption. It&#8217;s not possible to save partial result using only the utIsInterruptPending() function. However, it is possible to reset the interrupt state so that Matlab will not stop the execution after returning control from the mex function, and the caller function can get and use the partial calculation. The magic is done using another undocumented libut function named ​<i>utSetInterruptPending()</i>. A short example is included below (provided by Zvi Devir):</p>
<pre lang="cpp" highlight="4,14">
// Import libut functions
#pragma comment(lib, "libut.lib")
extern "C" bool utIsInterruptPending();
extern "C" bool utSetInterruptPending(bool);
// Run calculation divided into steps
int n;
for (n = 0; n < count; n++) {
	// some expensive calculation
	a_long_calculation(..., n);
	if (utIsInterruptPending()) {		// check for a Ctrl-C event
		mexPrintf("Ctrl-C detected [%d/%d].\n\n", n, count);
		utSetInterruptPending(false);	// Got it... consume event
		break;
	}
}
// Write back partial or full calculation
...
</pre>
<p>An elaboration of the idea of Ctrl-C detection was <a href="https://groups.google.com/d/msg/gerardus-users/m3rzaxHnmMM/eVo6K2WZxvYJ" rel="nofollow" target="_blank">created</a> by <a href="http://www.cs.ox.ac.uk/people/ramon.caserocanas/" rel="nofollow" target="_blank">Ramon Casero</a> (Oxford) for the <a href="https://github.com/rcasero/gerardus" rel="nofollow" target="_blank">Gerardus project</a>. Ramon wrapped Yin's code in C/C++ <code>#define</code> to create an easy-to-use pre-processor function <code>ctrlcCheckPoint(fileName,lineNumber)</code>:</p>
<pre lang="cpp">
...
ctrlcCheckPoint(__FILE__, __LINE__);  // exit if user pressed Ctrl+C
...
</pre>
<p>Here's the code for the preprocessor header file (<a href="https://github.com/rcasero/gerardus/blob/master/matlab/GerardusCommon.h" rel="nofollow" target="_blank"><i>GerardusCommon.h</i></a>) that #defines <code>ctrlcCheckPoint()</code> (naturally, the <code>__FILE__</code> and <code>__LINE__</code> parts could also be made part of the #define, for even simpler usage):</p>
<pre lang="cpp">
 /*
  * Author: Ramon Casero <rcasero@gmail.com>
  * Copyright © 2011-2013 University of Oxford
  * Version: 0.10.2
  *
  * University of Oxford means the Chancellor, Masters and Scholars of
  * the University of Oxford, having an administrative office at
  * Wellington Square, Oxford OX1 2JD, UK.
  *
  * This file is part of Gerardus.
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details. The offer of this
  * program under the terms of the License is subject to the License
  * being interpreted in accordance with English Law and subject to any
  * action against the University of Oxford being under the jurisdiction
  * of the English Courts.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see
  * <http://www.gnu.org/licenses/>.
  */
#ifndef GERARDUSCOMMON_H
#define GERARDUSCOMMON_H
/* mex headers */
#include <mex.h>
/* C++ headers */
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>
/* ITK headers */
#include "itkOffset.h"
/*
 * utIsInterruptPending(): "undocumented MATLAB API implemented in
 * libut.so, libut.dll, and included in the import library
 * libut.lib. To use utIsInterruptPending in a mex-file, one must
 * manually declare bool utIsInterruptPending() because this function
 * is not included in any header files shipped with MATLAB. Since
 * libut.lib, by default, is not linked by mex, one must explicitly
 * tell mex to use libut.lib." -- Wotao Yin,
 * http://www.caam.rice.edu/~wy1/links/mex_ctrl_c_trick/
 *
 */
#ifdef __cplusplus
    extern "C" bool utIsInterruptPending();
#else
    extern bool utIsInterruptPending();
#endif
/*
 * ctrlcCheckPoint(): function to check whether the user has pressed
 * Ctrl+C, and if so, terminate execution returning an error message
 * with a hyperlink to the offending function's help, and a hyperlink
 * to the line in the source code file this function was called from
 *
 * It is implemented as a C++ macro to check for the CTRL+C flag, and
 * a call to function ctrlcErrMsgTxt() inside, to throw the error. The
 * reason is that if ctrlcCheckPoint() were a function instead of a
 * macro, this would introduce a function call at every iteration of
 * the loop, which is very expensive. But then we don't want to put
 * the whole error message part inside a macro, it's bug-prone and bad
 * programming practice. And once the CTRL+C has been detected,
 * whether the error message is generated a bit faster or not is not
 * important.
 *
 * In practice, to use this function put a call like this e.g. inside
 * loops that may take for a very long time:
 *
 *    // exit if user pressed Ctrl+C
 *    ctrlcCheckPoint(__FILE__, __LINE__);
 *
 * sourceFile: full path and name of the C++ file that calls this
 *             function. This should usually be the preprocessor
 *             directive __FILE__
 *
 * lineNumber: line number where this function is called from. This
 *             should usually be the preprocessor directive __LINE__
 *
 */
inline
void ctrlcErrMsgTxt(std::string sourceFile, int lineNumber) {
  // run from here the following code in the Matlab side:
  //
  // >> path = mfilename('fullpath')
  //
  // this provides the full path and function name of the function
  // that called ctrlcCheckPoint()
  int nlhs = 1; // number of output arguments we expect
  mxArray *plhs[1]; // to store the output argument
  int nrhs = 1; // number of input arguments we are going to pass
  mxArray *prhs[1]; // to store the input argument we are going to pass
  prhs[0] = mxCreateString("fullpath"); // input argument to pass
  if (mexCallMATLAB(nlhs, plhs, nrhs, prhs, "mfilename")) { // run mfilename('fullpath')
    mexErrMsgTxt("ctrlcCheckPoint(): mfilename('fullpath') returned error");
  }
  if (plhs == NULL) {
    mexErrMsgTxt("ctrlcCheckPoint(): mfilename('fullpath') returned NULL array of outputs");
  }
  if (plhs[0] == NULL) {
    mexErrMsgTxt("ctrlcCheckPoint(): mfilename('fullpath') returned NULL output instead of valid path");
  }
  // get full path to current function, including function's name
  // (without the file extension)
  char *pathAndName = mxArrayToString(plhs[0]);
  if (pathAndName == NULL) {
    mexErrMsgTxt("ctrlcCheckPoint(): mfilename('fullpath') output cannot be converted to string");
  }
  // for some reason, using mexErrMsgTxt() to give this output
  // doesn't work. Instead, we have to give the output to the
  // standar error, and then call mexErrMsgTxt() to terminate
  // execution of the program
  std::cerr << "Operation terminated by user during "
	    << "<a href=\"matlab:helpUtils.errorDocCallback('"
	    << mexFunctionName()
	    << "', '" << pathAndName << ".m', " << lineNumber << ")\">"
	    << mexFunctionName()
	    << "</a> (<a href=\"matlab:opentoline('"
	    << sourceFile
	    << "'," << lineNumber << ",0)\">line " << lineNumber
	    << "</a>)"
	    << std::endl;
  mexErrMsgTxt("");
}
#define ctrlcCheckPoint(sourceFile, lineNumber)		\
  if (utIsInterruptPending()) {				\
    ctrlcErrMsgTxt(sourceFile, lineNumber);		\
  }
</pre>
<p>This feature has remained as-is since at least 2002 (when Peter first reported it), and apparently works to this day. Why then did I categorize this as "High risk for breaking in a future Matlab versions"? The reason is that internal undocumented MEX functions are prone to break in new Matlab releases (<a href="/articles/serializing-deserializing-matlab-data" target="_blank">example</a>). Hopefully my report today will prompt MathWorks to make this feature documented, rather than to remove it from a future release 🙂<br />
By the way, if anyone knows any use for the other interrupt-related functions in <i>libut</i> that I listed above, and/or the missing signatures, please leave a note below and I will update here accordingly.<br />
<b><u>Addendum July 2, 2016:</u></b> Pavel Holoborodko <a href="http://www.advanpix.com/2016/07/02/devnotes-3-proper-handling-of-ctrl-c-in-mex-module" rel="nofollow" target="_blank">just posted</a> an asynchronous version of this mechanism, which is an improvement of the synchronous code above. Pavel uses a separate Windows thread to check the Ctrl-C interrupt state. Readers can extend this idea to use threads for other asynchronous (multi-threaded) computations or I/O. In chapter 7 of my book "<a href="/books/matlab-java" rel="nofollow" target="_blank">Accelerating MATLAB Performance</a>" I explain how we can use Posix threads (pthreads) or OpenMP threads for similar multithreading in MEX (unlike Windows threads, pthreads and OpenMP are cross platform). Users can also use other multithreading solutions, such as the open-source Boost library (bundled with Matlab) or Intel's commercial TBB.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt">MEX ctrl-c interrupt</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/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/undocumented-feature-list" rel="bookmark" title="Undocumented feature list">Undocumented feature list </a> <small>A list of undocumented MATLAB features can be retrieved. Here's how... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-matlab-mex-api" rel="bookmark" title="Undocumented Matlab MEX API">Undocumented Matlab MEX API </a> <small>Matlab's MEX API contains numerous undocumented functions, that can be extremely useful. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/serializing-deserializing-matlab-data" rel="bookmark" title="Serializing/deserializing Matlab data">Serializing/deserializing Matlab data </a> <small>Matlab does not provide a documented manner to serialize data into a byte stream, but we can do this with some undocumented functionality. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Adding a search box to figure toolbar</title>
		<link>https://undocumentedmatlab.com/articles/adding-a-search-box-to-figure-toolbar?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=adding-a-search-box-to-figure-toolbar</link>
					<comments>https://undocumentedmatlab.com/articles/adding-a-search-box-to-figure-toolbar#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 30 Mar 2016 13:50:53 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Public presentation]]></category>
		<category><![CDATA[AppDesigner]]></category>
		<category><![CDATA[Internal component]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6353</guid>

					<description><![CDATA[<p>An interactive search-box can easily be added to a Matlab figure toolbar for enhanced user experience. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/adding-a-search-box-to-figure-toolbar">Adding a search box to figure toolbar</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/figure-toolbar-components" rel="bookmark" title="Figure toolbar components">Figure toolbar components </a> <small>Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to access existing toolbar icons and how to add non-button toolbar components....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/figure-toolbar-customizations" rel="bookmark" title="Figure toolbar customizations">Figure toolbar customizations </a> <small>Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to customize the Matlab figure toolbar....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-standard-figure-toolbar-menubar" rel="bookmark" title="Customizing the standard figure toolbar, menubar">Customizing the standard figure toolbar, menubar </a> <small>The standard figure toolbar and menubar can easily be modified to include a list of recently-used files....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Last week I wrote about my <a href="/articles/upcoming-public-matlab-presentations" target="_blank">upcoming presentations</a> in Tel Aviv and Munich, where I will discuss a Matlab-based financial application that uses some advanced GUI concepts. In today&#8217;s post I will review one of these concepts that could be useful in a wide range of Matlab applications &#8211; adding an interactive search box to the toolbar of Matlab figures.<br />
The basic idea is simple: whenever the user types in the search box, a Matlab callback function checks the data for the search term. If one or more matches are found then the searchbox&#8217;s background remains white, otherwise it is colored yellow to highlight the term. When the user presses &lt;Enter&gt;, the search action is triggered to highlight the term in the data, and any subsequent press of &lt;Enter&gt; will highlight the next match (cycling back at the top as needed). Very simple and intuitive:<br />
<center><figure style="width: 600px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Interactive search-box in Matlab figure toolbar" src="https://undocumentedmatlab.com/images/Pairformax_search_animated.gif" title="Interactive search-box in Matlab figure toolbar" width="600" height="345" /><figcaption class="wp-caption-text">Interactive search-box in Matlab figure toolbar</figcaption></figure></center><br />
<span id="more-6353"></span><br />
In my specific case, the search action (highlighting the search term in the data) involved doing a lot of work: updating multiple charts and synchronizing row selection in several connected uitables. For this reason, I chose not to do this action interactively (upon each keypress in the search box) but rather only upon clicking &lt;Enter&gt;. In your implementation, if the search action is simpler and faster, you could do it interactively for an even more intuitive effect.</p>
<h3 id="components">Technical components</h3>
<p>The pieces of today&#8217;s post were already discussed separately on this website, but never shown together as I will do today:</p>
<ul>
<li>The search box component (<code>com.mathworks.widgets.SearchTextField</code>) was discussed in last year&#8217;s article on <a href="/articles/auto-completion-widget" target="_blank">auto-completion widgets</a></li>
<li>I showed how to <a href="/articles/figure-toolbar-components" target="_blank">add custom controls to the figure toolbar</a> in a 2009 post (time flies!)</li>
<li>I discussed <a href="/articles/figure-toolbar-customizations" target="_blank">controlling toolbar components&#8217; size</a> in another old post</li>
<li>I discussed my <a href="/articles/findjobj-find-underlying-java-object" target="_blank"><i><b>findjobj</b></i> utility</a>, used for accessing the underlying Java components of Matlab uicontrols in another article</li>
<li>I discussed <a href="/articles/matlab-and-the-event-dispatch-thread-edt" target="_blank">Matlab&#8217;s use of EDT</a> in a dedicated article on the subject back in 2010 (and I&#8217;ll have more to say about this subject next week)</li>
<li>Finally, I discussed how to trap Java control events in Matlab in separate articles <a href="/articles/uicontrol-callbacks" target="_blank">here</a> and <a href="/articles/matlab-callbacks-for-java-events-in-r2014a" target="_blank">here</a></li>
</ul>
<h3 id="toolbar">Adding a search-box to the figure toolbar</h3>
<p>As a first step, let&#8217;s create the search-box component and add it to our figure&#8217;s toolbar:</p>
<pre lang="matlab">
% First, create the search-box component on the EDT, complete with invokable Matlab callbacks:
jSearch = com.mathworks.widgets.SearchTextField('Symbol');  % 'Symbol' is my default search prompt
jSearchPanel = javaObjectEDT(jSearch.getComponent);  % this is a com.mathworks.mwswing.MJPanel object
jSearchPanel = handle(jSearchPanel, 'CallbackProperties');  % enable Matlab callbacks
% Now, set a fixed size for this component so that it does not resize when the figure resizes:
jSize = java.awt.Dimension(100,25);  % 100px wide, 25px tall
jSearchPanel.setMaximumSize(jSize)
jSearchPanel.setMinimumSize(jSize)
jSearchPanel.setPreferredSize(jSize)
jSearchPanel.setSize(jSize)
% Now, attach the Matlab callback function to search box events (key-clicks, Enter, and icon clicks):
jSearchBox = handle(javaObjectEDT(jSearchPanel.getComponent(0)), 'CallbackProperties');
set(jSearchBox, 'ActionPerformedCallback', {@searchSymbol,hFig,jSearchBox})
set(jSearchBox, 'KeyPressedCallback',      {@searchSymbol,hFig,jSearchBox})
jClearButton = handle(javaObjectEDT(jSearchPanel.getComponent(1)), 'CallbackProperties');
set(jClearButton, 'ActionPerformedCallback', {@searchSymbol,hFig,jSearchBox})
% Now, get the handle for the figure's toolbar:
hToolbar = findall(hFig,'tag','FigureToolBar');
jToolbar = get(get(hToolbar,'JavaContainer'),'ComponentPeer');  % or: hToolbar.JavaContainer.getComponentPeer
% Now, justify the search-box to the right of the toolbar using an invisible filler control
% (first add the filler control to the toolbar, then the search-box control):
jFiller = javax.swing.Box.createHorizontalGlue;  % this is a javax.swing.Box$Filler object
jToolbar.add(jFiller,      jToolbar.getComponentCount);
jToolbar.add(jSearchPanel, jToolbar.getComponentCount);
% Finally, refresh the toolbar so that the new control is displayed:
jToolbar.revalidate
jToolbar.repaint
</pre>
<h3 id="search">Search action callback functionality</h3>
<p>Now that the control is displayed in the toolbar, let&#8217;s define what our Matlab callback function <i>searchSymbol()</i> does. Remember that this callback function is invoked whenever any of the possible events occur: keypress, &lt;Enter&gt;, or clicking the search-box&#8217;s icon (typically the &#8220;x&#8221; icon, to clear the search term).<br />
We first reset the search-box appearance (foreground/background colors), then we check the search term (if non-empty). Based on the selected tab, we search the corresponding data table&#8217;s symbol column(s) for the search term. If no match is found, we highlight the search term by setting the search-box&#8217;s text to be red over yellow. Otherwise, we change the table&#8217;s selected row to the next match&#8217;s row index (i.e., the row following the table&#8217;s currently-selected row, cycling back at the top of the table if no match is found lower in the table).<br />
Reading and updating the table&#8217;s selected row requires using my <a href="/articles/findjobj-find-underlying-java-object" target="_blank"><i><b>findjobj</b></i> utility</a> &#8211; for performance considerations the jTable handle should be cached (perhaps in the hTable&#8217;s <b>UserData</b> or <b>ApplicationData</b>):</p>
<pre lang="matlab">
% Callback function to search for a symbol
function searchSymbol(hObject, eventData, hFig, jSearchBox)
    try
        % Clear search-box formatting
        jSearchBox.setBackground(java.awt.Color.white)
        jSearchBox.setForeground(java.awt.Color.black)
        jSearchBox.setSelectedTextColor(java.awt.Color.black)
        jSearchBox.repaint
        % Search for the specified symbol in the data table
        symbol = char(jSearchBox.getText);
        if ~isempty(symbol)
            handles = guidata(hFig);
            hTab = handles.hTabGroup.SelectedTab;
            colOffset = 0;
            forceCol0 = false;
            switch hTab.Title
                case 'Scanning'
                    hTable = handles.tbScanResults;
                    symbols = cell(hTable.Data(:,1));
                case 'Correlation'
                    hTable = handles.tbCorrResults;
                    symbols = cell(hTable.Data(:,1:2));
                case 'Backtesting'
                    hTab = handles.hBacktestTabGroup.SelectedTab;
                    hTable = findobj(hTab, 'Type','uitable', 'Tag','results');
                    pairs = cell(hTable.Data(:,1));
                    symbols = cellfun(@(c)strsplit(c,'/'), pairs, 'uniform',false);
                    symbols = reshape([symbols{:}],2,[])';
                    forceCol0 = true;
                case 'Trading'
                    hTable = handles.tbTrading;
                    symbols = cell(hTable.Data(:,2:3));
                    colOffset = 1;
                otherwise  % ignore
                    return
            end
            if isempty(symbols)
                return
            end
            [rows,cols] = ind2sub(size(symbols), find(strcmpi(symbol,symbols)));
            if isempty(rows)
                % Not found - highlight the search term
                jSearchBox.setBackground(java.awt.Color.yellow)
                jSearchBox.setForeground(java.awt.Color.red)
                jSearchBox.setSelectedTextColor(java.awt.Color.red)
                jSearchBox.repaint
            elseif isa(eventData, 'java.awt.event.KeyEvent') && isequal(eventData.getKeyCode,10)
                % Found with <enter> event - highlight the relevant data row
                jTable = findjobj(hTable);
                try jTable = jTable.getViewport.getView; catch, end  % in case findjobj returns the containing scrollpane rather than the jTable
                [rows, sortedIdx] = sort(rows);
                cols = cols(sortedIdx);
                currentRow = jTable.getSelectedRow + 1;
                idx = find(rows>currentRow,1);
                if isempty(idx),  idx = 1;  end
                if forceCol0
                    jTable.changeSelection(rows(idx)-1, 0, false, false)
                else
                    jTable.changeSelection(rows(idx)-1, cols(idx)-1+colOffset, false, false)
                end
                jTable.repaint
                jTable.getTableHeader.repaint
                jTable.getParent.getParent.repaint
                drawnow
            end
        end
    catch
        % never mind - ignore
    end
end
</pre>
<p>That&#8217;s all there is to it. In my specific case, changing the table&#8217;s selected row cased an immediate trigger that updated the associated charts, synchronized the other data tables and did several other background tasks.</p>
<h3 id="uifigure">What about the new web-based uifigure?</h3>
<p>The discussion above refers only to traditional Matlab <i><b>figure</b></i>s (both HG1 and HG2), not to the new web-based (AppDesigner) <i><b>uifigure</b></i>s that were officially introduced in R2016a (I <a href="/articles/sliders-in-matlab-gui#AppDesigner" target="_blank">wrote about it</a> last year).<br />
AppDesigner uifigures are basically webpages rather than desktop windows (JFrames). They use an entirely different UI mechanism, based on HTML webpages served from a localhost webserver, using the <a href="https://dojotoolkit.org" rel="nofollow" target="_blank">DOJO Javascript toolkit</a> for visualization and interaction, rather than Java Swing as in the existing JFrame figures. The existing figures still work without change, and are expected to continue working alongside the new uifigures for the foreseeable future. I&#8217;ll discuss the new uifigures in separate future posts (in the meantime you can read a bit about them in <a href="/articles/sliders-in-matlab-gui#AppDesigner" target="_blank">my post</a> from last year).<br />
I suspect that the new uifigures will replace the old figures at some point in the future, to enable a fully <a href="/articles/online-web-based-matlab" target="_blank">web-based (online) Matlab</a>. Will this happen in 2017 or 2027 ? &#8211; your guess is as good as mine, but my personal guesstimate is around 2018-2020.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/adding-a-search-box-to-figure-toolbar">Adding a search box to figure toolbar</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/figure-toolbar-components" rel="bookmark" title="Figure toolbar components">Figure toolbar components </a> <small>Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to access existing toolbar icons and how to add non-button toolbar components....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/figure-toolbar-customizations" rel="bookmark" title="Figure toolbar customizations">Figure toolbar customizations </a> <small>Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to customize the Matlab figure toolbar....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-standard-figure-toolbar-menubar" rel="bookmark" title="Customizing the standard figure toolbar, menubar">Customizing the standard figure toolbar, menubar </a> <small>The standard figure toolbar and menubar can easily be modified to include a list of recently-used files....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/adding-a-search-box-to-figure-toolbar/feed</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Programmatic shortcuts manipulation &#8211; part 2</title>
		<link>https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=programmatic-shortcuts-manipulation-part-2</link>
					<comments>https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-2#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 30 Dec 2015 16:42:52 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6169</guid>

					<description><![CDATA[<p>Non-standard shortcut controls and customizations can easily be added to the Matlab desktop. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-2">Programmatic shortcuts manipulation &#8211; part 2</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/programmatic-shortcuts-manipulation-part-1" rel="bookmark" title="Programmatic shortcuts manipulation &#8211; part 1">Programmatic shortcuts manipulation &#8211; part 1 </a> <small>Matlab Desktop shortcuts can be programmatically accessed and customized. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/command-window-text-manipulation" rel="bookmark" title="Command Window text manipulation">Command Window text manipulation </a> <small>Special control characters can be used to format text output in Matlab's Command Window. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons" rel="bookmark" title="Matlab toolstrip – part 5 (icons)">Matlab toolstrip – part 5 (icons) </a> <small>Icons can be specified in various ways for toolstrip controls and the app window itself. ...</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>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Today I will expand <a target="_blank" href="/articles/programmatic-shortcuts-manipulation-part-1">last week&#8217;s post</a> on customizing Matlab Desktop&#8217;s shortcuts. I will show that we can incorporate non-standard controls, and add tooltips and user callbacks in undocumented ways that are not available using the interactive Desktop GUI.<br />
<center><figure style="width: 584px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Custom shortcut controls" src="https://undocumentedmatlab.com/images/Shortcuts4c.png" title="Custom shortcut controls" width="584" height="182" /><figcaption class="wp-caption-text">Custom shortcut controls</figcaption></figure></center><br />
<span id="more-6169"></span><br />
Today&#8217;s article will focus on the new toolstrip interface of Matlab release R2012b and later; adaptation of the code to R2012a and earlier is relatively easy (in fact, simpler than the toolstrip-based code below).</p>
<h3 id="panel">Displaying the Shortcuts panel</h3>
<p>Before we begin to modify shortcuts in the Toolstrip&#8217;s shortcuts menu, we need to ensure that the Shortcuts panel is visible and active (in current focus), otherwise our customizations will be ignored or cause an error. There is probably a more direct way of doing this, but a simple way that I found was to edit the current Desktop&#8217;s layout to include a directive to display the Shortcuts tab, and then load that layout:</p>
<pre lang='matlab'>
jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance;
hMainFrame = com.mathworks.mde.desk.MLDesktop.getInstance.getMainFrame;
jToolstrip = hMainFrame.getToolstrip;
isOk = jToolstrip.setCurrentTab('shortcuts');
if ~isOk  % i.e., Shortcuts tab is NOT displayed
    % Save the current Desktop layout
    jDesktop.saveLayout('Yair');  pause(0.15);
    % Update the layout file to display the Shortcuts tab
    filename = fullfile(prefdir, 'YairMATLABLayout.xml');
    fid = fopen(filename, 'rt');
    txt = fread(fid, '*char')';
    fclose(fid);
    txt = regexprep(txt,'(ShowShortcutsTab=)"[^"]*"','');
    txt = regexprep(txt,'(<layout [^>]*)>','$1 ShowShortcutsTab="yes">');
    fid = fopen(filename, 'wt');
    fwrite(fid,txt);
    fclose(fid);
    % Load the modified layout
    jDesktop.restoreLayout('Yair');  pause(0.15);
    % The shortcuts tab should now be visible, so transfer focus to that tab
    jToolstrip.setCurrentTab('shortcuts');
end
</pre>
<h3 id="custom">Custom controls</h3>
<p>As I explained in <a target="_blank" href="/articles/programmatic-shortcuts-manipulation-part-1#in-session">last week&#8217;s post</a>, we can use <code>scUtils.addShortcutToBottom</code> to add a simple push-button shortcut to the relevant category panel within the Shortcuts toolstrip tab. To add custom controls, we can simply add the controls to the relevant shortcut category panel container (a <code>com.mathworks.toolstrip.components.TSPanel</code> object). The standard shortcuts are typically placed in the Shortcuts tab&#8217;s second <code>TSPanel</code> (&#8220;general&#8221;), and other categories have <code>TSPanel</code>s of their own.<br />
Now here&#8217;s the tricky part about <code>TSPanel</code>s: we cannot directly add components to the sectino panel (that would be too easy&#8230;): the section panels are composed of an array of internal <code>TSPanel</code>s, and we need to add the new controls to those internal panels. However, these panels only contain 3 empty slots. If we try to add more than 3 components, the 4th+ component(s) will simply not be displayed. In such cases, we need to create a new <code>TSPanel</code> to display the extra components.<br />
Here then is some sample code to add a combo-box (drop-down) control:</p>
<pre lang='matlab'>
% First, get the last internal TSPanel within the Shortcuts tab's "general" section panel
% Note: jToolstrip was defined in the previous section above
jShortcutsTab = jToolstrip.getModel.get('shortcuts').getComponent;
jSectionPanel = jShortcutsTab.getSectionComponent(1).getSection.getComponent;  % the TSPanel object "general"
jContainer = jSectionPanel.getComponent(jSectionPanel.getComponentCount-1);
% If the last internal TSPanel is full, then prepare a new internal TSPanel next to it
if jContainer.getComponentCount >= 3
    % Create a new empty TSPanel and add it to the right of the last internal TSPanel
    jContainer = com.mathworks.toolstrip.components.TSPanel;
    jContainer.setPreferredSize(java.awt.Dimension(100,72));
    jSectionPanel.add(jContainer);
    jSectionPanel.repaint();
    jSectionPanel.revalidate();
end
% Create the new control with a custom tooltip and callback function
optionStrings = {'Project A', 'Project B', 'Project C'};
jCombo = com.mathworks.toolstrip.components.TSComboBox(optionStrings);
jCombo = handle(javaObjectEDT(jCombo), 'callbackproperties'));
set(jCombo, 'ActionPerformedCallback', @myCallbackFunction);
jCombo.setToolTipText('Select the requested project');
% Now add the new control to the internal TSPanel
jContainer.add(jCombo);
jContainer.repaint();
jContainer.revalidate();
</pre>
<p><center><figure style="width: 555px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Custom shortcut controls" src="https://undocumentedmatlab.com/images/Shortcuts4a.png" title="Custom shortcut controls" width="555" height="236" /><figcaption class="wp-caption-text">Custom shortcut controls</figcaption></figure></center><br />
Matlab&#8217;s internal <code>com.mathworks.toolstrip.components</code> package contains many embeddable controls, including the following (I emphasized those that I think are most useful within the context of the Shortcuts panel): <code><b>TSButton</b></code>, <code><b>TSCheckBox</b></code>, <code><b>TSComboBox</b></code>, <code>TSDropDownButton</code> (a custom combo-box component), <code>TSFormattedTextField</code>, <code>TSLabel</code>, <code><b>TSList</b></code>, <code><b>TSRadioButton</b></code>, <code>TSScrollPane</code>, <code><b>TSSlider</b></code>, <code><b>TSSpinner</b></code>, <code>TSSplitButton</code>, <code>TSTextArea</code>, <code><b>TSTextField</b></code>, and <code><b>TSToggleButton</b></code>. These controls are in most cases simple wrappers of the corresponding Java Swing controls. For example, <code>TSSpinner</code> extends the standard Swing <a target="_blank" rel="nofollow" href="https://docs.oracle.com/javase/tutorial/uiswing/components/spinner.html"><code>JSpinner</code> control</a>. In some cases, the controls are more complex: for example, the <code>TSSplitButton</code> is similar to Matlab&#8217;s <a target="_blank" href="/articles/uisplittool-uitogglesplittool"><i><b>uisplittool</b></i> control</a>.<br />
<center><figure style="width: 430px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Toolstrip controls" src="https://undocumentedmatlab.com/images/Toolstrip_components.png" title="Toolstrip controls" width="430" height="140" /><figcaption class="wp-caption-text">Toolstrip controls</figcaption></figure></center><br />
In fact, these controls can be used even outside the toolstrip, embedded directly in our Matlab figure GUI, using the <a target="_blank" href="/articles/javacomponent"><i><b>javacomponent</b></i> function</a>. For example:</p>
<pre lang='matlab'>
dataModel = javax.swing.SpinnerNumberModel(125, 15, 225, 0.5);  % defaultValue, minValue, maxValue, stepSize
jSpinner = com.mathworks.toolstrip.components.TSSpinner(dataModel);
jSpinner = handle(javaObjectEDT(jSpinner), 'CallbackProperties');
[hjSpinner, hContainer] = javacomponent(jSpinner, [10,10,60,20], gcf);
</pre>
<p>You can find additional interesting components within the <i>%matlabroot%/java/jar/toolstrip.jar</i> file, which can be opened in any zip file utility or Java IDE. In fact, whatever controls that you see Matlab uses in its Desktop toolstrip (including galleries etc.) can be replicated in custom tabs, sections and panels of our own design.<br />
Matlab Desktop&#8217;s interactive GUI only enables creating simple push-button shortcuts having string callbacks (that are <i><b>eval</b></i>&#8216;ed in run-time). Using the undocumented programmatic interface that I just showed, we can include more sophisticated controls, as well as customize those controls in ways that are impossible via the programmatic GUI: add tooltips, set non-string (function-handle) callbacks, enable/disable controls, modify icons in run-time etc.<br />
For example (intentionally showing two separate ways of setting the component properties):</p>
<pre lang='matlab'>
% Toggle-button
jTB = handle(javaObjectEDT(com.mathworks.toolstrip.components.TSToggleButton('Toggle button')), 'CallbackProperties')
jTB.setSelected(true)
jTB.setToolTipText('toggle me!')
jTB.ActionPerformedCallback = @(h,e)doSomething();
jContainer.add(jTB);
% Check-box
jCB = handle(javaObjectEDT(com.mathworks.toolstrip.components.TSCheckBox('selected !')), 'CallbackProperties');
set(jCB, 'Selected', true, 'ToolTipText','Please select me!', 'ActionPerformedCallback',{@myCallbackFunction,extraData});
jContainer.add(jCB);
</pre>
<p>(resulting in the screenshot at the top of this post)<br />
<u><b>Important note</b></u>: none of these customizations is saved to file. Therefore, they need to be redone programmatically for each separate Matlab session. You can easily do that by calling the relevant code in your <i>startup.m</i> file.<br />
If you wish me to assist with any customization of the Desktop shortcuts, or any other Matlab aspect, then <a target="_blank" href="/contact">contact me</a> for a short consultancy.<br />
Happy New Year everybody!</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-2">Programmatic shortcuts manipulation &#8211; part 2</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/programmatic-shortcuts-manipulation-part-1" rel="bookmark" title="Programmatic shortcuts manipulation &#8211; part 1">Programmatic shortcuts manipulation &#8211; part 1 </a> <small>Matlab Desktop shortcuts can be programmatically accessed and customized. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/command-window-text-manipulation" rel="bookmark" title="Command Window text manipulation">Command Window text manipulation </a> <small>Special control characters can be used to format text output in Matlab's Command Window. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons" rel="bookmark" title="Matlab toolstrip – part 5 (icons)">Matlab toolstrip – part 5 (icons) </a> <small>Icons can be specified in various ways for toolstrip controls and the app window itself. ...</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>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-2/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Programmatic shortcuts manipulation &#8211; part 1</title>
		<link>https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-1?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=programmatic-shortcuts-manipulation-part-1</link>
					<comments>https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-1#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 23 Dec 2015 11:08:05 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Icons]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6146</guid>

					<description><![CDATA[<p>Matlab Desktop shortcuts can be programmatically accessed and customized. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-1">Programmatic shortcuts manipulation &#8211; part 1</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/programmatic-shortcuts-manipulation-part-2" rel="bookmark" title="Programmatic shortcuts manipulation &#8211; part 2">Programmatic shortcuts manipulation &#8211; part 2 </a> <small>Non-standard shortcut controls and customizations can easily be added to the Matlab desktop. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/command-window-text-manipulation" rel="bookmark" title="Command Window text manipulation">Command Window text manipulation </a> <small>Special control characters can be used to format text output in Matlab's Command Window. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-type-selection-components" rel="bookmark" title="Plot-type selection components">Plot-type selection components </a> <small>Several built-in components enable programmatic plot-type selection in Matlab GUI - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/r2009b-keyboard-bindings" rel="bookmark" title="R2009b keyboard bindings">R2009b keyboard bindings </a> <small>The new Matlab release R2009b includes the ability to customize keyboard bindings for the editor and Command Window. However, there are still some uses for the EditorMacro utility and its variants....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>User-defined shortcuts can interactively be added to the Matlab Desktop to enable easy access to often-used scripts (e.g., clearing the console, running a certain program, initializing data etc.). Similarly, we can place shortcuts in the help browser to quickly access often-used pages. Unfortunately, both of these shortcut functionalities, like many other functionalities of the Matlab Desktop and related tools (Editor, Browser, Profiler etc.), have no documented programmatic access.<br />
Such programmatic access is often useful. For example, a large company for which I consult is using centralized updates to users&#8217; shortcuts, in order to manage and expose new features for all Matlab users from a central location. It is easy to send updates and manage a few users, but when your organization has dozens of Matlab users, centralized management becomes a necessity. It&#8217;s a pity that companies need to resort to external consultants and undocumented hacks to achieve this, but I&#8217;m not complaining since it keeps me occupied&#8230;<br />
<center><figure style="width: 320px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Shortcuts in Matlab R2012a and earlier" src="https://undocumentedmatlab.com/images/Shortcuts1_R2010a.png" title="Shortcuts in Matlab R2012a and earlier" width="320" height="190" /><figcaption class="wp-caption-text">Shortcuts in Matlab R2012a and earlier</figcaption></figure><br />
<figure style="width: 585px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Shortcuts in Matlab R2012b and newer" src="https://undocumentedmatlab.com/images/Shortcuts1_R2016a.png" title="Shortcuts in Matlab R2012b and newer" width="585" height="180" /><figcaption class="wp-caption-text">Shortcuts in Matlab R2012b and newer</figcaption></figure><br />
</center><br />
Today&#8217;s post will describe &#8220;regular&#8221; shortcuts &#8211; those that are simple clickable buttons. Next week I will show how we can extend this to incorporate other types of shortcut controls, as well as some advanced customizations.<br />
<span id="more-6146"></span></p>
<h3 id="xml">The <i>shortcuts.xml</i> file</h3>
<p>It turns out that the shortcults toolbar (on R2012a and earlier) or toolstrip group (on R2012b onward) is a reflection of the contents of the <i>[prefdir &#8216;\shortcuts.xml&#8217;]</i> file (depending on your version, the file might be named somewhat differently, i.e. <i>shortcuts_2.xml</i>). This file can be edited in any text editor, Matlab&#8217;s editor included. So a very easy way to programmatically affect the shortcuts is to update this file. Here is a sample of this file:</p>
<pre lang='xml'>
<?xml version="1.0" encoding="utf-8"?>
<favoritesroot version="2">
   <title>My Shortcuts</title>
   <favoritecategory>
      <name>Help Browser Favorites</name>
      <favorite>
         <label>Help Using the Desktop</label>
         <icon>Help icon</icon>
         <callback>helpview([docroot '/mapfiles/matlab_env.map'], 'matlabenvironment_desktop');</callback>
         <editable>true</editable>
      </favorite>
   </favoritecategory>
   <favorite>
      <label>CSSM</label>
      <icon>Help icon</icon>
      <callback>disp('No callback specified for this shortcut')</callback>
      <editable>true</editable>
   </favorite>
   <favorite>
      <label>UndocML</label>
      <icon>MATLAB icon</icon>
      <callback>web('undocumentedMatlab.com')</callback>
      <editable>true</editable>
   </favorite>
   <favorite>
      <label>My favorite program</label>
      <icon>C:\Yair\program\icon.gif</icon>
      <callback>cd('C:\Yair\program'); myProgram(123);</callback>
      <editable>true</editable>
   </favorite>
   ...
</favoritesroot>
</pre>
<p>The file is only loaded once during Matlab startup, so any changes made to it will only take effect after Matlab restarts.</p>
<h3 id="in-session">Updating the shortcuts in the current Matlab session</h3>
<p>We can update the shortcuts directly, in the current Matlab session, using the builtin <code>com.mathworks.mlwidgets.shortcuts.­ShortcutUtils</code> class. This class has existed largely unchanged for numerous releases (at least as far back as R2008b).<br />
For example, to add a new shortcut to the toolbar:</p>
<pre lang='matlab'>
name = 'My New Shortcut';
cbstr = 'disp(''My New Shortcut'')';  % will be eval'ed when clicked
iconfile = 'c:\path\to\icon.gif';  % default icon if it is not found
isEditable = 'true';
scUtils = com.mathworks.mlwidgets.shortcuts.ShortcutUtils;
category = scUtils.getDefaultToolbarCategoryName;
scUtils.addShortcutToBottom(name,cbstr,iconfile,category,isEditable);
</pre>
<p>The shortcut&#8217;s icon can either be set to a specific icon filepath (e.g., &#8216;C:\Yair\program\icon.jpg&#8217;), or to one of the predefined names: &#8216;Help icon&#8217;, &#8216;Standard icon&#8217;, &#8216;MATLAB icon&#8217; or &#8216;Simulink icon&#8217;. The <code>editable</code> parameter does not seem to have a visible effect that I could see.<br />
The category name can either be set to the default name using <code>scUtils.getDefaultToolbarCategoryName</code> (&#8216;Shortcuts&#8217; on English-based Matlab R2012b onward), or it can be set to any other name (e.g., &#8216;My programs&#8217;). To add a shortcut to the Help Browser (also known as a &#8220;Favorite&#8221;), simply set the category to <code>scUtils.getDefaultHelpCategoryName</code> (=&#8217;Help Browser Favorites&#8217; on English-based Matlab installations); to add the shortcut to the &#8216;Start&#8217; button, set the category to &#8216;Shortcuts&#8217;. When you use a non-default category name on R2012a and earlier, you will only see the shortcuts via Matlab&#8217;s &#8220;Start&#8221; button (as seen in the screenshot below); on R2012b onward you will see it as a new category group within the Shortcuts toolstrip (as seen in the screenshot above). For example:</p>
<pre lang='matlab'>
scUtils = com.mathworks.mlwidgets.shortcuts.ShortcutUtils;
scUtils.addShortcutToBottom('clear', 'clear; clc', 'Standard icon', 'Special commands', 'true');
</pre>
<p><center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Custom category in Matlab R2010a" src="https://undocumentedmatlab.com/images/Shortcuts2_R2010a.png" title="Custom category in Matlab R2010a" width="450" height="527" /><figcaption class="wp-caption-text">Custom category in Matlab R2010a</figcaption></figure></center><br />
To remove a shortcut, use the <i>removeShortcut(category,shortcutName)</i> method (note: this method does not complain if the specified shortcut does not exist):</p>
<pre lang='matlab'>scUtils.removeShortcut('Shortcuts', 'My New Shortcut');</pre>
<p>The <i>addShortcutToBottom()</i> method does not override existing shortcuts. Therefore, to ensure that we don&#8217;t add duplicate shortcuts, we must first remove the possibly-existing shortcut using <i>removeShortcut()</i> before adding it. Since <i>removeShortcut()</i> does not complain if the specific shortcut is not found, we can safely use it without having to loop over all the existing shortcuts. Alternately, we could loop over all existing category shortcuts checking their label, and adding a new shortcut only if it is not already found, as follows:</p>
<pre lang='matlab'>
scUtils = com.mathworks.mlwidgets.shortcuts.ShortcutUtils;
category = scUtils.getDefaultToolbarCategoryName;
scVector = scUtils.getShortcutsByCategory(category);
scArray = scVector.toArray;  % Java array
foundFlag = 0;
for scIdx = 1:length(scArray)
   scName = char(scArray(scIdx));
   if strcmp(scName, 'My New Shortcut')
      foundFlag = 1; break;
      % alternatively: scUtils.removeShortcut(category, scName);
   end
end
if ~foundFlag
   scUtils.addShortcutToBottom(scName, callbackString, iconString, category, 'true');
end
</pre>
<p>As noted above, we can add categories by simply specifying a new category name in the call to <i>scUtils.addShortcutToBottom()</i>. We can also add and remove categories directly, as follows (beware: when removing a category, it is removed together with all its contents):</p>
<pre lang='matlab'>
scUtils.addNewCategory('category name');
scUtils.removeShortcut('category name', []);  % entire category will be deleted
</pre>
<h3 id="FEX">Shortcut tools on the Matlab File Exchange</h3>
<p>Following <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/2802233/programmatically-configure-matlab">my advice on StackOverflow</a> back in 2010, Richie Cotton wrapped the code snippets above in a user-friendly utility (set of independent Matlab functions) that can now be found on the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/27567-shortcut-tools">Matlab File Exchange</a> and on <a target="_blank" rel="nofollow" href="http://4dpiecharts.com/2010/08/23/a-shortcut-to-success/">his blog</a>. Richie tested his toolbox on Matlab releases as old as R2008b, but the functionality may also work on even older releases.</p>
<h3 id="panel">Shortcuts panel embedded in Matlab GUI</h3>
<p>Shortcuts are normally visible in the toolbar and the Matlab start menu (R2012a and earlier) or the Matlab Desktop&#8217;s toolstrip (R2012b onward). However, using <code>com.mathworks.mlwidgets.shortcuts.ShortcutTreePanel</code>, the schortcuts can also be displayed in any user GUI, complete with right-click context-menu:</p>
<pre lang='matlab'>
jShortcuts = com.mathworks.mlwidgets.shortcuts.ShortcutTreePanel;
[jhShortcuts,hPanel] = javacomponent(jShortcuts, [10,10,300,200], gcf);
</pre>
<p><center><figure style="width: 323px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Shortcuts panel in Matlab figure GUI" src="https://undocumentedmatlab.com/images/Shortcuts3.png" title="Shortcuts panel in Matlab figure GUI" width="323" height="296" /><figcaption class="wp-caption-text">Shortcuts panel in Matlab figure GUI</figcaption></figure></center></p>
<h3 id="followup">Stay tuned&#8230;</h3>
<p>Next week I will expand the discussion of Matlab shortcuts with the following improvements:</p>
<ol>
<li>Displaying non-standard controls as shortcuts: checkboxes, drop-downs (combo-boxes) and toggle-buttons</li>
<li>Customizing the shortcut tooltip (replacing the default tooltip that simply repeats the callback string)</li>
<li>Customizing the shortcut callback (rather than using an <i><b>eval</b></i>-ed callback string)</li>
<li>Enabling/disabling shortcuts in run-time</li>
</ol>
<p>Merry Christmas everyone!</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-1">Programmatic shortcuts manipulation &#8211; part 1</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/programmatic-shortcuts-manipulation-part-2" rel="bookmark" title="Programmatic shortcuts manipulation &#8211; part 2">Programmatic shortcuts manipulation &#8211; part 2 </a> <small>Non-standard shortcut controls and customizations can easily be added to the Matlab desktop. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/command-window-text-manipulation" rel="bookmark" title="Command Window text manipulation">Command Window text manipulation </a> <small>Special control characters can be used to format text output in Matlab's Command Window. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-type-selection-components" rel="bookmark" title="Plot-type selection components">Plot-type selection components </a> <small>Several built-in components enable programmatic plot-type selection in Matlab GUI - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/r2009b-keyboard-bindings" rel="bookmark" title="R2009b keyboard bindings">R2009b keyboard bindings </a> <small>The new Matlab release R2009b includes the ability to customize keyboard bindings for the editor and Command Window. However, there are still some uses for the EditorMacro utility and its variants....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-1/feed</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>Font selection components</title>
		<link>https://undocumentedmatlab.com/articles/font-selection-components?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=font-selection-components</link>
					<comments>https://undocumentedmatlab.com/articles/font-selection-components#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 07 Oct 2015 17:45:06 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[JIDE]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6013</guid>

					<description><![CDATA[<p>Several built-in components enable programmatic font selection in Matlab GUI - this article explains how. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/font-selection-components">Font selection components</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/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/color-selection-components" rel="bookmark" title="Color selection components">Color selection components </a> <small>Matlab has several internal color-selection components that can easily be integrated in Matlab GUI...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-type-selection-components" rel="bookmark" title="Plot-type selection components">Plot-type selection components </a> <small>Several built-in components enable programmatic plot-type selection in Matlab GUI - this article explains how...</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>I&#8217;ve written here in the past about how Matlab includes multiple alternatives for <a target="_blank" href="/articles/color-selection-components">color selection</a>, <a target="_blank" href="/articles/plot-type-selection-components">plot-type selection</a> and <a target="_blank" href="/articles/date-selection-components">date selection</a> components, that can easily be integrated in Matlab figures (GUI). Today, I will show that Matlab also contains various built-in components for font selection.<br />
These components are used by Matlab itself, integrated within the Preferences panel, print setup popup, property inspector window and so on. In most cases the components have remained unchanged for multiple releases, some existing in Matlab releases for the past decade or more. However, since internal components can change without prior notice, there is no assurance that any particular component will continue to be available in future Matlab releases.<br />
Readers who are interested in additional details about the components mentioned in today&#8217;s post are referred to sections 3.3.3 and 5.5.2 of my book, <i><a target="_blank" href="/books/matlab-java">Undocumented Secrets of MATLAB-Java Programming</a></i>.</p>
<h3 id="uisetfont">uisetfont</h3>
<p>The only documented font-selection alternative in Matlab is <i><b>uisetfont</b></i>, which presents a popup dialog window that returns the selected font properties in a simple Matlab struct:</p>
<pre lang='matlab'>
>> font = uisetfont
font =
      FontName: 'Arial'
    FontWeight: 'normal'
     FontAngle: 'normal'
     FontUnits: 'points'
      FontSize: 10
</pre>
<p><center><figure style="width: 367px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Matlab's uisetfont dialog" src="https://undocumentedmatlab.com/images/uisetfont.png" title="Matlab's uisetfont dialog" width="367" height="363" /><figcaption class="wp-caption-text">Matlab's <i><b>uisetfont</b></i> dialog</figcaption></figure></center><br />
<span id="more-6013"></span><br />
The main drawback of <i><b>uisetfont</b></i> is the fact that it displays a separate non-resizable modal dialog window. We cannot embed <i><b>uisetfont</b></i> within our own panel, integrated in our GUI figure.</p>
<h3 id="DesktopFontPicker">DesktopFontPicker</h3>
<p><code>DesktopFontPicker</code> is a Swing component that presents a font selection panel that can easily be inserted into any Matlab GUI container (figure, panel or tab) using <a target="_blank" href="/articles/javacomponent">the <i><b>javacomponent</b></i> function</a>:</p>
<pre lang='matlab'>
font = java.awt.Font('Tahoma',java.awt.Font.PLAIN, 11);
jFontPanel = com.mathworks.widgets.DesktopFontPicker(true, font);
[jhPanel,hContainer] = javacomponent(jFontPanel, [10,10,250,170], gcf);
</pre>
<p><center><figure style="width: 250px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="DesktopFontPicker panel" src="https://undocumentedmatlab.com/images/DesktopFontPicker.gif" title="DesktopFontPicker panel" width="250" height="170" /><figcaption class="wp-caption-text"><code>DesktopFontPicker</code> panel</figcaption></figure></center><br />
Instead of the “Use desktop font” label, we can use our own label:</p>
<pre lang='matlab'>jFontPanel.setUseDesktopFontLabel('Use Yair''s standard font...')</pre>
<p><center><figure style="width: 347px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Non-standard DesktopFontPicker panel" src="https://undocumentedmatlab.com/images/DesktopFontPicker2.png" title="Non-standard DesktopFontPicker panel" width="347" height="290" /><figcaption class="wp-caption-text">Non-standard <code>DesktopFontPicker</code> panel</figcaption></figure></center><br />
To extract the selected font, use one of the following methods provided by <code>DesktopFontPicker</code>:</p>
<pre lang='matlab'>
jFont = jFontPanel.getSelectedFont();  % returns a java.awt.Font object
flag = jFontPanel.getUseDesktopFont();  % true if top radio-button is selected; false if custom font is selected
</pre>
<h3 id="FontPrefsPanel">FontPrefsPanel</h3>
<p>The builtin <code>com.mathworks.mlwidgets.prefs.FontPrefsPanel</code> class is used in Matlab to display the font preferences panel in the Preferences window. We can integrate it directly in our GUI:</p>
<pre lang='matlab'>
jFontPanel=com.mathworks.mlwidgets.prefs.FontPrefsPanel(java.awt.Dimension);
[jhPanel,hContainer] = javacomponent(jFontPanel, [1,1,500,470], gcf);
</pre>
<p>Using this class is admittedly more cumbersome than <code>DesktopFontPicker</code> and I would not recommend using it in practice.</p>
<h3 id="FontPicker">FontPicker</h3>
<p>Font selection can also be shown with drop-downs (combo-boxes), rather than with lists as in <code>DesktopFontPicker</code>, <code>FontPrefsPanel</code>, or <i><b>uisetfont</b></i>. Use of drop-downs significantly reduces the display &#8220;real-estate&#8221; required by the control. This is useful in forms where the font selection is only one of several user-configurable options, and where enough space must be reserved for other configuration controls. We can do this using the <code>com.mathworks.widgets.fonts.FontPicker</code> class.<br />
Up until Matlab release R2010a, <code>FontPicker</code>&#8216;s constructor accepted optional parameters of a pre-selected font (a <code>java.awt.Font</code> object), an optional boolean flag indicating whether to display sample text using the selected font, an optional layout indicator, and optional list of selectable font names. Several screenshots of different parameter combinations are shown below:</p>
<pre lang='matlab'>
import com.mathworks.widgets.fonts.FontPicker
jFontPicker = FontPicker(font, sampleFlag, layout);
[hjFontPicker, hContainer] = javacomponent(jFontPicker, position, gcf);
</pre>
<table style="background: white; border: none;">
<tbody style="text-align: center;">
<tr>
<td style="border: none;"> </td>
<td style="border: none;"><img loading="lazy" decoding="async" alt="FontPicker" src="https://undocumentedmatlab.com/images/FontPicker1.png" title="FontPicker" width="140" height="40" /></td>
<td style="border: none;"><img loading="lazy" decoding="async" alt="FontPicker" src="https://undocumentedmatlab.com/images/FontPicker2.png" title="FontPicker" width="225" height="20" /></td>
<td style="border: none;"><img loading="lazy" decoding="async" alt="FontPicker" src="https://undocumentedmatlab.com/images/FontPicker3.png" title="FontPicker" width="225" height="80" /></td>
</tr>
<tr>
<td>font=</td>
<td>[]</td>
<td><code>java.awt.Font('Tahoma', java.awt.Font.PLAIN, 8 )</code></td>
<td>[]</td>
</tr>
<tr>
<td>sampleFlag=</td>
<td><code>false</code></td>
<td><code>false</code></td>
<td><code>true</code></td>
</tr>
<tr>
<td>layout=</td>
<td><code>FontPicker.GRID_LAYOUT</code> (=1)</td>
<td><code>FontPicker.LONG_LAYOUT</code> (=2)</td>
<td><code>FontPicker.LONG_LAYOUT</code> (=2)</td>
</tr>
<tr>
<td>position=</td>
<td>[10,200,140,40]</td>
<td>[10,200,225,20]</td>
<td>[10,200,225,80]</td>
</tr>
</tbody>
</table>
<p>As before, the selected font can be retrieved using <code>jFontPicker.getSelectedFont()</code>.<br />
In Matlab release R2010b, <code>FontPicker</code>&#8216;s interface changed, and the above code no longer works. This highlights a common pitfall in future-compatibility of internal components: even when the components remain, their interface sometimes changes. Here is the new code format, starting with R2010b:</p>
<pre lang='matlab'>
jLayout = javaMethod('valueOf', 'com.mathworks.widgets.fonts.FontPicker$Layout', 'WIDE_WITH_SAMPLE');  % options: COMPACT, WIDE, WIDE_WITH_SAMPLE
jFont = java.awt.Font('Tahoma', java.awt.Font.PLAIN, 10);  % initial font to display (may not be [])
jFontPicker = com.mathworks.widgets.fonts.FontPicker(jFont, jLayout);
jFontPanel = jFontPicker.getComponent;
[jhPanel,hContainer] = javacomponent(jFontPanel, [10,10,250,120], gcf);
</pre>
<h3 id="FontChooserPanel">FontChooserPanel</h3>
<p>As a final alternative for font selection, we can use the JIDE font-selection component. This component has two variants: as a drop-down/combo-box (<code>com.jidesoft.combobox.FontComboBox</code>) and as a standard <code>JPanel</code> (<code>com.jidesoft.combobox.FontChooserPanel</code>):</p>
<pre lang='matlab'>
jFont = java.awt.Font('arial black',java.awt.Font.PLAIN, 8);
jFontPicker = com.jidesoft.combobox.FontComboBox(jFont);
[hjFontPicker, hContainer] = javacomponent(jFontPicker, position, gcf);
set(hjFontPicker, 'ItemStateChangedCallback', @myCallbackFunction);
</pre>
<p><center><figure style="width: 264px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="JIDE's FontComboBox" src="https://undocumentedmatlab.com/images/JIDE_FontComboBox.png" title="JIDE's FontComboBox" width="264" height="254" /><figcaption class="wp-caption-text">JIDE's FontComboBox</figcaption></figure></center><br />
Within the callback function, use <i>getSelectedFont()</i> to retrieve the updated font (again, a <code>java.awt.Font</code> object). There is also a corresponding <i>setSelectedFont(font)</i> to programmatically update the control with the specified <code>Font</code> object.<br />
The combo-box presents a <code>FontChooserPanel</code>, which can be accessed (via the <b>PopupPanel</b> property or the corresponding <i>getPopupPanel()</i> method) after it has been initially created. Thereafter, the panel can be customized. For example, the preview text can be modified via the panel&#8217;s <b>PreviewText</b> property (or the <i>setPreviewText(text)</i> method).<br />
The same <code>FontChooserPanel</code> can also be displayed as a stand-alone font-selection panel, unrelated to any combo-box. Different GUI requirements might prefer using a compact combo-box approach, or the larger stand-alone panel.<br />
This combo-box/panel duality is a common feature of JIDE controls. I have previously shown it in my <a target="_blank" href="/articles/color-selection-components">color selection components</a> and <a target="_blank" href="/articles/date-selection-components">date selection components</a> articles.</p>
<h3 id="uicontrol">popupmenu uicontrol</h3>
<p>As another example of using a font-selection drop-down (combo-box), we can use a standard Matlab popupmenu <i><b>uicontrol</b></i>, setting its <b>String</b> property value to a cell-array containing the supported system&#8217;s fonts (as returned by the <i><b>listfonts</b></i> function). A nice twist here is to use the undocumented trick that all <a target="_blank" href="/articles/html-support-in-matlab-uicomponents">Matlab uicontrols inherently support HTML</a> to list each of the fonts in their respective font style:</p>
<pre lang='matlab'>
fontStr = @(font) ['<html><font face="' font '">' font '</font></html>'];
htmlStr = cellfun(fontStr, listfonts, 'uniform',false);
uicontrol('style','popupmenu', 'string',htmlStr, 'pos',[20,350,100,20]);
</pre>
<p><center><figure style="width: 355px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="HTML-rendered fonts popup menu" src="https://undocumentedmatlab.com/images/html_fonts.png" title="HTML-rendered fonts popup menu" width="355" height="460" /><figcaption class="wp-caption-text">HTML-rendered fonts popup menu</figcaption></figure></center><br />
Note that we could also use a listbox <i><b>uicontrol</b></i> using the same code.</p>
<h3 id="Austria">Austria visit, 11-15 October, 2015</h3>
<p>I will be travelling to clients in Austria next week, between October 11-15. If you are in Austria and wish to meet me to discuss how I could bring value to your work, then please email me (altmany at gmail).</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/font-selection-components">Font selection components</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/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/color-selection-components" rel="bookmark" title="Color selection components">Color selection components </a> <small>Matlab has several internal color-selection components that can easily be integrated in Matlab GUI...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-type-selection-components" rel="bookmark" title="Plot-type selection components">Plot-type selection components </a> <small>Several built-in components enable programmatic plot-type selection in Matlab GUI - this article explains how...</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/font-selection-components/feed</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
	</channel>
</rss>
