<?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>Java &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/category/java/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Sun, 10 Feb 2019 17:00:10 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
	<item>
		<title>Matlab toolstrip – part 9 (popup figures)</title>
		<link>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-toolstrip-part-9-popup-figures</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 10 Feb 2019 17:00:10 +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[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8402</guid>

					<description><![CDATA[<p>Custom popup figures can be attached to Matlab GUI toolstrip controls. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures">Matlab toolstrip – part 9 (popup figures)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization" rel="bookmark" title="Matlab toolstrip – part 4 (control customization)">Matlab toolstrip – part 4 (control customization) </a> <small>Matlab toolstrip components (controls) can be customized in various ways, including user-defined callbacks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app" rel="bookmark" title="Matlab toolstrip – part 2 (ToolGroup App)">Matlab toolstrip – part 2 (ToolGroup App) </a> <small>Matlab users can create custom Apps with toolstrips and docked figures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-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>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In <a href="https://undocumentedmatlab.com/articles/tag/toolstrip" target="_blank">previous posts</a> I showed how we can create custom Matlab app toolstrips using various controls. Today I will show how we can incorporate popup forms composed of Matlab figures into our Matlab toolstrip. These are similar in concept to drop-down and gallery selectors, in the sense that when we click the toolstrip button a custom popup is displayed. In the case of a popup form, this is a fully-customizable Matlab GUI figure.<br />
<center><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_popup_figure.png" alt="Popup figure in Matlab toolstrip" title="Popup figure in Matlab toolstrip" width="80%" style="max-width:605px;" /></center><br />
Toolstrips can be a bit complex to develop so I&#8217;m proceeding slowly, with each post in the miniseries building on the previous posts. <span id="more-8402"></span> I encourage you to review the earlier posts in the <a href="https://undocumentedmatlab.com/articles/tag/toolstrip" target="_blank">Toolstrip miniseries</a> before reading this post.<br />
Also, remember to add the following code snippet at the beginning of your code so that the relevant toolstrip classes will be recognized by Matlab:</p>
<pre lang="matlab">import matlab.ui.internal.toolstrip.*</pre>
<h3 id="steps">Main steps and usage example</h3>
<p>To attach a figure popup to a toolstrip control, follow these steps:</p>
<ol>
<li>Create a new figure, using GUIDE or the <i><b>figure</b></i> function. The figure should typically be created modal and non-visible, unless there&#8217;s a good reason to avoid this. Note that the figure needs to be a legacy (Java-based) figure, created with GUIDE or the <i><b>figure</b></i> function &#8212; web-based uifigure (created with AppDesigner or the <i><b>uifigure</b></i> function) is not [currently] supported. </li>
<li>Create a callback function that opens and initializes this figure, and then moves it to the expected screen location using the following syntax: <code>hToolGroup.showFigureDialog(hFig,hAnchor)</code>, where <code>hFig</code> is the figure&#8217;s handle, and <code>hAnchor</code> is the handle for the triggering toolstrip control.</li>
<li>Attach the callback function to the triggering toolstrip control.</li>
</ol>
<p>Here&#8217;s a simple usage example, in which I present a file-selector popup:</p>
<pre lang="matlab">
% Create a toolstrip section, column & push-button
hSection = hTab.addSection('Popup');
hColumn = hSection.addColumn();
hButton = Button('Open',Icon.OPEN_24);
hButton.ButtonPushedFcn = {@popupFigure,hButton};  % attach popup callback to the button
hColumn.add(hButton);
% Callback function invoked when the toolstrip button is clicked
function popupFigure(hAction, hEventData, hButton)
    % Create a new non-visible modal figure
    hFig = figure('MenuBar','none', 'ToolBar','none', 'WindowStyle','modal', ...
                  'Visible','off', 'NumberTitle','off', 'Name','Select file:');
    % Add interactive control(s) to the figure (in this case, a file chooser initialized to current folder)
    jFileChooser = handle(javaObjectEDT(javax.swing.JFileChooser(pwd)), 'CallbackProperties');
    [jhFileChooser, hComponent] = javacomponent(jFileChooser, [0,0,200,200], hFig);
    set(hComponent, 'Units','normalized', 'Position',[0,0,1,1]);  % resize component within containing figure
    % Set popup control's callback (in this case, display the selected file and close the popup)
    jhFileChooser.ActionPerformedCallback = @popupActionPerformedCallback;
    function popupActionPerformedCallback(jFileChooser, jEventData)
        fprintf('Selected file: %s\n', char(jFileChooser.getSelectedFile));
        delete(hFig);
    end
    % Display the popup figure onscreen, just beneath the triggering button
    showFigureDialog(hToolGroup,hFig,hButton);
    % Wait for the modal popup figure to close before resuming GUI interactivity
    waitfor(hFig);
end
</pre>
<p>This leads to the popup figure as shown in the screenshot above.<br />
The popup figure initially appears directly beneath the triggering button. The figure can then be moved away from that position, by dragging its title bar or border frame.<br />
Note how the popup is an independent heavy-weight figure window, having a border frame, title bar and a separate task-bar icon. Removing the border frame and title-bar of Matlab figures can be done using an <a href="https://undocumentedmatlab.com/articles/frameless-undecorated-figure-windows" target="_blank">undocumented visual illusion</a> &#8211; this can make the popup less obtrusive, but also prevent its moving/resizing. An entirely different and probably better approach is to present a light-weight popup panel using the Toolpack framework, which I plan to discuss in the following post(s). The <a href="https://undocumentedmatlab.com/articles/builtin-popuppanel-widget" target="_blank"><code>PopupPanel</code> container</a> that I discussed in another post <i>cannot</i> be used, because it is displayed as a sub-component of a Matlab figure, and in this case the popup is not attached to any figure (the toolstrip and ToolGroup are not Matlab figures, <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app" target="_blank">as explained here</a>).<br />
The astute reader may wonder why I bothered going to all the trouble of displaying a modal popup with a <code>JFileChooser</code>, when I could have simply used the built-in <i><b>uigetfile</b></i> or <i><b>uiputfile</b></i> functions in the button&#8217;s callback. The answer is that (a) this mechanism displays the popup directly beneath the triggering button using <code>hToolGroup.showFigureDialog()</code>, and also (b) enables complex popups (dialogs) that have no direct builtin Matlab function (for example, a <a href="https://undocumentedmatlab.com/articles/uigetfile-uiputfile-customizations" target="_blank">file-selector with preview</a>, or a <a href="https://undocumentedmatlab.com/articles/using-spinners-in-matlab-gui" target="_blank">multi-component input form</a>).</p>
<h3 id="compatibility">Compatibility considerations for R2018a or older</h3>
<p>In Matlab releases R2018a or older that do not have the <i>hToolGroup.showFigureDialog()</i> function, you can create it yourself in a separate <i>showFigureDialog.m</i> file, as follows:</p>
<pre lang="matlab">
function showFigureDialog(hToolGroup, hFig, hAnchor)
    %   showFigureDialog - Display a figure-based dialog below a toolstrip control.
    %
    %   Usage example:
    %       showFigureDialog(hToolGroup, hFig, hAnchor);
    %   where:
    %       "hToolGroup" must be a "matlab.ui.internal.desktop.ToolGroup" handle
    %       "hFig" must be a "figure" handle, not a "uifigure"
    %       "hAnchor" must be a "matlab.ui.internal.toolstrip.***" handle
    %hWarn = ctrlMsgUtils.SuspendWarnings('MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame'); %#ok<nasgu>
    hWarn = warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
    jf = get(hFig, 'JavaFrame');
    if isempty(jf)
        error('UI figure cannot be added to "ToolGroup". Use a regular figure instead.')
    else
        screen_size = get(0,'ScreenSize');
        old_pos = get(hFig,'OuterPosition');
        dpi_ratio = com.mathworks.util.ResolutionUtils.scaleSize(100)/100;
        jAnchor = hToolGroup.ToolstripSwingService.Registry.getWidgetById(hAnchor.getId());
        pt = javaMethodEDT('getLocationOnScreen',jAnchor); % pt is anchor top left
        pt.y = pt.y + jAnchor.getVisibleRect().height;     % pt is anchor bottom left
        new_x = pt.getX()/dpi_ratio-5;                           % figure outer left
        new_y = screen_size(end)-(pt.getY/dpi_ratio+old_pos(4)); % figure outer bottom
        hFig.OuterPosition = [new_x new_y old_pos(3) old_pos(4)];
        hFig.Visible = 'on';
    end
    warning(hWarn);
end
</pre>
<h3 id="showFigureDialog">Under the hood of <i>showFigureDialog()</i></h3>
<p>How does <i>showFigureDialog()</i> know where to place the figure, directly beneath the triggering toolstrip anchor?<br />
The answer is really quite simple, if you look at this method&#8217;s source-code in <i>%matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+desktop/ToolGroup.m</i> (around line 500, depending on the Matlab release).<br />
The function first checks whether the input <code>hFig</code> handle belongs to a figure or uifigure, and issues an error message in case it&#8217;s a uifigures (only legacy figures are currently supported).<br />
Then the function fetches the toolstrip control&#8217;s underlying Java control handle using the following code (slightly modified for clarity), <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization#Java" target="_blank">as explained here</a>:</p>
<pre lang="matlab">jAnchor = hToolGroup.ToolstripSwingService.Registry.getWidgetById(hAnchor.getId());</pre>
<p>Next, it uses the Java control&#8217;s <i>getLocationOnScreen()</i> to get the control&#8217;s onscreen position, accounting for monitor DPI variation that affects the X location.<br />
The figure&#8217;s <b>OuterPosition</b> property is then set so that the figure&#8217;s top-left corner is exactly next to the control&#8217;s bottom-left corner.<br />
Finally, the figure&#8217;s <b>Visible</b> property is set to &#8216;on&#8217; to make the figure visible in its new position.<br />
The popup figure&#8217;s location is recomputed by <i>showFigureDialog()</i> whenever the toolstrip control is clicked, so the popup figure is presented in the expected position even when you move or resize the tool-group window.</p>
<h3 id="roadmap">Toolstrip miniseries roadmap</h3>
<p>The following post(s) will present the Toolpack framework. Non-figure (lightweight) popup toolpack panels can be created, which appear more polished/stylish than the popup figures that I presented today. The drawdown is that toolpack panels may be somewhat more complex to program than figures, and IMHO are more likely to change across Matlab releases. In addition to the benefit of popup toolpack panels, toolpack presents an alternative way for toolstrip creation and customization, enabling programmers to choose between using the toolstrip framework (that I discussed so far), and the new toolpack framework.<br />
In a succeeding post, I&#8217;ll discuss toolstrip collapsibility, i.e. what happens when the user resizes the window, reducing the toolstrip width. Certain toolstrip controls will drop their labels, and toolstrip sections shrink into a drop-down. The priority of control/section collapsibility can be controlled, so that less-important controls will collapse before more-important ones.<br />
In future posts, I plan to discuss docking layout, DataBrowser panel, QAB (Quick Access Bar), underlying Java controls, and adding toolstrips to figures &#8211; not necessarily in this order.<br />
Matlab toolstrips can be a bit complex, so I plan to proceed in small steps, each post building on top of its predecessors.<br />
If you would like me to assist you in building a custom toolstrip or GUI for your Matlab program, <a href="https://undocumentedmatlab.com/consulting" target="_blank">please let me know</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures">Matlab toolstrip – part 9 (popup figures)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization" rel="bookmark" title="Matlab toolstrip – part 4 (control customization)">Matlab toolstrip – part 4 (control customization) </a> <small>Matlab toolstrip components (controls) can be customized in various ways, including user-defined callbacks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app" rel="bookmark" title="Matlab toolstrip – part 2 (ToolGroup App)">Matlab toolstrip – part 2 (ToolGroup App) </a> <small>Matlab users can create custom Apps with toolstrips and docked figures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-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>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Matlab toolstrip – part 5 (icons)</title>
		<link>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-toolstrip-part-5-icons</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 06 Jan 2019 17:00:37 +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[Icons]]></category>
		<category><![CDATA[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8188</guid>

					<description><![CDATA[<p>Icons can be specified in various ways for toolstrip controls and the app window itself. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons">Matlab toolstrip – part 5 (icons)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization" rel="bookmark" title="Matlab toolstrip – part 3 (basic customization)">Matlab toolstrip – part 3 (basic customization) </a> <small>Matlab toolstrips can be created and customized in a variety of ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app" rel="bookmark" title="Matlab toolstrip – part 2 (ToolGroup App)">Matlab toolstrip – part 2 (ToolGroup App) </a> <small>Matlab users can create custom Apps with toolstrips and docked figures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In a <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization" target="_blank">previous post</a> I showed how we can create custom Matlab app toolstrips. Toolstrips can be a bit complex to develop so I’m trying to proceed slowly, with each post in the miniseries building on the previous posts. I encourage you to review the earlier posts in <a href="https://undocumentedmatlab.com/articles/tag/toolstrip" target="_blank">the Toolstrip miniseries</a> before reading this post. Today&#8217;s post describes how we can set various icons, based on the toolstrip created in the previous posts:<br />
<center><figure style="width: 440px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_basic_controls.png" alt="Toolstrip example (basic controls)" title="Toolstrip example (basic controls)" width="100%" style="max-width:553px; margin:0" /><figcaption class="wp-caption-text">Toolstrip example (basic controls)</figcaption></figure></center><br />
<span id="more-8188"></span></p>
<h3 id="components">Component icons</h3>
<p>Many toolstrip controls (such as buttons, but not checkboxes for example) have a settable <b>Icon</b> property. The standard practice is to use a 16&#215;16 icon for a component within a multi-component toolstrip column (i.e., when 2 or 3 components are displayed on top of each other), and a 24&#215;24 icon for a component that spans the entire column height (i.e., when the column contains only a single component).<br />
We can use one of the following methods to specify the icon. Note that you need to <code>import matlab.ui.internal.toolstrip.*</code> if you wish to use the <code>Icon</code> class without the preceding package name.</p>
<ul>
<li>The <b>Icon</b> property value is typically empty (<code>[]</code>) by default, meaning that no icon is displayed.<br />
&nbsp;
</li>
<li>We can use one of ~150 standard icons using the format <code>Icon.&lt;icon-name&gt;</code>. For example: <code>icon = Icon.REFRESH_24</code>. These icons typically come in 2 sizes: 16&#215;16 pixels (e.g. Icon.REFRESH_16) that we can use with the small-size components (which are displayed when the column has 2-3 controls), and 24&#215;24 pixels (e.g. REFRESH_24) that we can use with the large-size components (which are displayed when the column contains only a single control). You can see the list of the standard icons by running
<pre lang="matlab">matlab.ui.internal.toolstrip.Icon.showStandardIcons</pre>
<p><center><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_standard_icons.png" alt="Standard toolstrip control Icons" title="Standard toolstrip control Icons" width="50%" style="max-width:658px;" /></center></li>
<li>We can use the <code>Icon</code> constructor by specifying the full filepath for any PNG or JPG image file. Note that other file type (such as GIF) are not supported by this method. For example:
<pre lang="matlab">icon = Icon(fullfile(matlabroot,'toolbox','matlab','icons','tool_colorbar.png')); % PNG/JPG image file (not GIF!)</pre>
<p>In fact, the ~150 standard icons above use this mechanism under the hood: <code>Icon.REFRESH_24</code> is basically a public static method of the <code>Icon</code> class, which simply calls <code>Icon('REFRESH_24','Refresh_24')</code>  (note the undocumented use of a 2-input <code>Icon</code> constructor). This method in turn uses the <i>Refresh_24.png</i> file in Matlab&#8217;s standard toolstrip resources folder: <i>%matlabroot%/toolbox/shared/controllib/general/resources/toolstrip_icons/Refresh_24.png</i>.</p>
<li>We can also use the <code>Icon</code> constructor by specifying a PNG or JPG file contained within a JAR file, using the standard <code>jar:file:...jar!/</code> notation. There are numerous icons included in Matlab&#8217;s JAR files &#8211; simply open these files in WinZip or WinRar and browse. In addition, you can include images included in any external JAR file. For example:
<pre lang="matlab">icon = Icon(['jar:file:/' matlabroot '/java/jar/mlwidgets.jar!/com/mathworks/mlwidgets/actionbrowser/resources/uparrow.png']);</pre>
</li>
<li>We can also use the <code>Icon</code> constructor by specifying a Java <code>javax.swing.ImageIcon</code> object. Fortunately we can create such objects from a variety of image formats (including GIFs). For example:
<pre lang="matlab">
iconFilename = fullfile(matlabroot,'toolbox','matlab','icons','boardicon.gif');
jIcon = javax.swing.ImageIcon(iconFilename);  % Java ImageIcon from file (inc. GIF)
icon = Icon(jIcon);
</pre>
<p>If we need to resize the Java image (for example, from 16&#215;16 to 24&#215;24 or vise versa), we can use the following method:</p>
<pre lang="matlab">
% Resize icon to 24x24 pixels
jIcon = javax.swing.ImageIcon(iconFilename);  % get Java ImageIcon from file (inc. GIF)
jIcon = javax.swing.ImageIcon(jIcon.getImage.getScaledInstance(24,24,jIcon.getImage.SCALE_SMOOTH))  % resize to 24x24
icon = Icon(jIcon);
</pre>
</li>
<li>We can apparently also use a CSS class-name to load images. This is only relevant for the JavaScript-based uifigures, not legacy Java-based figures that I discussed so far. Perhaps I will explore this in some later post that will discuss toolstrip integration in uifigures.</li>
</ul>
<h3 id="app">App window icon</h3>
<p>The app window&#8217;s icon can also be set. By default, the window uses the standard Matlab membrane icon (<i>%matlabroot%/toolbox/matlab/icons/matlabicon.gif</i>). This can be modified using the <code>hToolGroup.setIcon</code> method, which currently [R2018b] expects a Java <code>ImageIcon</code> object as input. For example:</p>
<pre lang="matlab">
iconFilename = fullfile(matlabroot,'toolbox','matlab','icons','reficon.gif');
jIcon = javax.swing.ImageIcon(iconFilename);
hToolGroup.setIcon(jIcon)
</pre>
<p>This icon should be set before the toolgroup window is shown (<code>hToolGroup.open</code>).<br />
<center><figure style="width: 400px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_app_icon.gif" alt="Custom app window icon" title="Custom app window icon" width="400" height="230" /><figcaption class="wp-caption-text">Custom app window icon</figcaption></figure></center><br />
An odd caveat here is that the icon size needs to be 16&#215;16 &#8211; setting a larger icon results in the icon being ignored and the default Matlab membrane icon used. For example, if we try to set &#8216;boardicon.gif&#8217; (16&#215;17) instead of &#8216;reficon.gif&#8217; (16&#215;16) we&#8217;d get the default icon instead. If our icon is too large, we can resize it to 16&#215;16, as shown above:</p>
<pre lang="matlab">
% Resize icon to 16x16 pixels
jIcon = javax.swing.ImageIcon(iconFilename);  % get Java ImageIcon from file (inc. GIF)
jIcon = javax.swing.ImageIcon(jIcon.getImage.getScaledInstance(16,16,jIcon.getImage.SCALE_SMOOTH))  % resize to 16x16
hToolGroup.setIcon(jIcon)
</pre>
<p>It&#8217;s natural to expect that <code>hToolGroup</code>, which is a pure-Matlab MCOS wrapper class, would have an <b>Icon</b> property that accepts <code>Icon</code> objects, just like for controls as described above. For some reason, this is not the case. It&#8217;s very easy to fix it though &#8211; after all, the <code>Icon</code> class is little more than an MCOS wrapper class for the underlying Java <code>ImageIcon</code> (not exactly, but close enough). Adapting <code>ToolGroup</code>&#8216;s code to accept an <code>Icon</code> is quite easy, and I hope that MathWorks will indeed implement this in a near-term future release. I also hope that MathWorks will remove the 16&#215;16 limitation, or automatically resize icons to 16&#215;16, or at the very least issue a console warning when a larger icon is specified by the user. Until then, we can use the <code>setIcon(jImageIcon)</code> method and take care to send it the 16&#215;16 <code>ImageIcon</code> object that it expects.</p>
<h3 id="roadmap">Toolstrip miniseries roadmap</h3>
<p>The next post will discuss complex components, including button-group, drop-down, listbox, split-button, slider, popup form, gallery etc.<br />
Following that, my plan is to discuss toolstrip collapsibility, the ToolPack framework, docking layout, DataBrowser panel, QAB (Quick Access Bar), underlying Java controls, and adding toolstrips to figures &#8211; not necessarily in this order. Matlab toolstrips can be a bit complex, so I plan to proceed in small steps, each post building on top of its predecessors.<br />
If you would like me to assist you in building a custom toolstrip or GUI for your Matlab program, <a href="https://undocumentedmatlab.com/consulting" target="_blank">please let me know</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons">Matlab toolstrip – part 5 (icons)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization" rel="bookmark" title="Matlab toolstrip – part 3 (basic customization)">Matlab toolstrip – part 3 (basic customization) </a> <small>Matlab toolstrips can be created and customized in a variety of ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app" rel="bookmark" title="Matlab toolstrip – part 2 (ToolGroup App)">Matlab toolstrip – part 2 (ToolGroup App) </a> <small>Matlab users can create custom Apps with toolstrips and docked figures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Matlab toolstrip – part 2 (ToolGroup App)</title>
		<link>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-toolstrip-part-2-toolgroup-app</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 05 Dec 2018 17:00:48 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<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[schema.prop]]></category>
		<category><![CDATA[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8059</guid>

					<description><![CDATA[<p>Matlab users can create custom Apps with toolstrips and docked figures. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app">Matlab toolstrip – part 2 (ToolGroup App)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-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-1" rel="bookmark" title="Matlab toolstrip &#8211; part 1">Matlab toolstrip &#8211; part 1 </a> <small>Matlab contains extensive toolstrip (ribbon) functionality that can be integrated in user programs (GUI). ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A while ago I posted the first of my planned miniseries on the <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1" target="_blank">Matlab toolstrip (ribbon)</a>. Today I will expand that post by discussing how toolstrips can be added to Matlab GUIs. This post will remain at a high-level as the previous post, with followup posts drilling into the technical details of the toolstrip components (inner packages and classes).<br />
We can add a Matlab toolstrip to 3 types of Matlab GUI windows:</p>
<ol>
<li>To a Java-based Matlab figure (so-called &#8220;legacy&#8221; figures, created using GUIDE or the <i><b>figure</b></i> function)</li>
<li>To a container window of docked Java-based figures, typically called an &#8220;App&#8221; (marketing name) or &#8220;Tool Group&#8221; (internal technical name)</li>
<li>To a JavaScript/HTML-based Matlab figure (so called &#8220;web&#8221; figures, created using App Designer or the <i><b>uifigure</b></i> function)</li>
</ol>
<p>Today I will show how to add a basic dynamic toolstrip to a ToolGroup (App, window type #2):<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_2c_animated.gif" alt="ToolGroup with clients and dynamic toolstrip" title="ToolGroup with clients and dynamic toolstrip" width="450" height="314" /><figcaption class="wp-caption-text">ToolGroup with clients and dynamic toolstrip</figcaption></figure></center><br />
<span id="more-8059"></span></p>
<h3 id="ToolGroup">Figure containers (&#8220;Tool Groups&#8221;)</h3>
<p>Most Matlab users are familiar with window types #1 and #3 (legacy and web-based figures), but type #2 may seem strange. In fact, it shouldn&#8217;t be: All the Matlab &#8220;Apps&#8221; and Desktop components use such a container of docked clients. For example, both the Matlab Editor and Desktop are containers of individual client windows (individual files in the Editor; Command Window, Workspace etc. in the desktop).<br />
Similarly, when we dock figures, they dock as client windows into a container called &#8220;Figures&#8221; (this can be controlled programmatically: see my <a href="https://www.mathworks.com/matlabcentral/fileexchange/16650-setfigdockgroup" rel="nofollow" target="_blank"><i><b>setFigDockGroup</b></i> utility</a> on the File Exchange). This is the basis for all Matlab &#8220;Apps&#8221;, as far as I am aware (some Apps may possibly use a different GUI container, after all there are ~100 Matlab Apps and I&#8217;m not familiar with all of them). Such Apps are basically stand-alone Tool Groups (client container windows) that contain one or more docked figures, a toolstrip, and a side-panel with controls (so-called &#8220;Data Browser&#8221;).<br />
Note: MathWorks uses confusing terminology here, using the same term &#8220;App&#8221; for both MathWorks-created GUIs containers (that have toolstrips, Data Browser and docked figures) and also user-created utilities on the File Exchange (that do not have these). Unfortunately, MathWorks has chosen not [yet] to release to the general public its set of tools that enable creating true &#8220;Apps&#8221;, i.e. those that have a toolstrip, Data Browser and docked figures.<br />
Today&#8217;s post will attempt to fill this gap, by showing how we can create user Apps that have a toolstrip and docked figures. I will ignore the Data Browser today, and will describe it in a future post. Since docking figures into a standalone user-created container is a solved problem (using my <a href="https://www.mathworks.com/matlabcentral/fileexchange/16650-setfigdockgroup" rel="nofollow" target="_blank"><i><b>setFigDockGroup</b></i> utility</a>), this post will focus on adding a toolstrip to such a container.<br />
A ToolGroup object (<code>matlab.ui.internal.desktop.ToolGroup</code>) is created either implicitly (by docking a figure into a group that has a new name), or explicitly (by invoking its constructor):</p>
<pre lang="matlab">
% Create a new non-visible empty App (Tool Group)
hToolGroup = matlab.ui.internal.desktop.ToolGroup('Toolstrip example on UndocumentedMatlab.com');
</pre>
<p>Some things only work properly after the app is displayed, so let&#8217;s display the ToolGroup (however, note that for improved performance it is better to do whatever customizations and GUI updates that you can before the app is made visible):</p>
<pre lang="matlab">
% Display the ToolGroup window
hToolGroup.open();
</pre>
<p><center><figure style="width: 435px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_2b.png" alt="Basic empty ToolGroup (without toolstrip or clients)" title="Basic empty ToolGroup (without toolstrip or clients)" width="435" height="347" /><figcaption class="wp-caption-text">Basic empty ToolGroup (without toolstrip or clients)</figcaption></figure></center><br />
An annoying quirk with ToolGroups is that they automatically close when their reference handle is deleted from Matlab memory. The specific behavior changes depending on the contents of the container and the Matlab release, but in general it&#8217;s safest to preserve the <code>hToolGroup</code> variable, to prevent the window from closing, when this variable goes out of scope, when the function (in which we create the ToolGroup) returns. There are many ways to persist this variable. Here&#8217;s one alternative, in which we persist it in itself (or rather, attached to its internal Java peer control):</p>
<pre lang="matlab">
% Store toolgroup reference handle so that app will stay in memory
jToolGroup = hToolGroup.Peer;
internal.setJavaCustomData(jToolGroup, hToolGroup);
</pre>
<p><b><i>internal.setJavaCustomData</i></b> is an undocumented Matlab function that adds a new custom property to a Java reference handle. In our case, it adds a <b>CustomData</b> property to the <code>jToolGroup</code> handle and sets its value to the Matlab <code>hToolGroup</code> handle. The source code for <b><i>internal.setJavaCustomData</i></b> is available in <i>%matlabroot%/toolbox/shared/controllib/general/+internal/setJavaCustomData.m</i> and is very simple: it essentially uses the old <code>schema</code>-based <a href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles" target="_blank"><i><b>schema.prop</b></i></a> method for adding new properties to handles. <code>Schema</code> is an old deprecated mechanism that is mostly replaced by the newer MCOS (Matlab Class Object System), but for some specific cases such as this it&#8217;s still very useful (the standard <a href="https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects" target="_blank"><i><b>addprop</b></i> function</a> can add new properties to Matlab GUI handles, but not to Java reference handles).<br />
Finally, let&#8217;s discard the Data Browser side panel (I&#8217;ll discuss it in a separate future post):</p>
<pre lang="matlab">
% Discard the Data-browser left panel
hToolGroup.disableDataBrowser();
</pre>
<h3 id="toolstrip">Adding a toolstrip to the ToolGroup</h3>
<p>Now that we have the basic container ready, let&#8217;s add a toolstrip. To simplify matters in this introductory post (after all, I have still not described the internal packages and classes that make up a toolstrip), we&#8217;ll use some of the tabs used in the <code>showcaseToolGroup</code> example that I discussed in <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1" target="_blank">my previous post</a>. You can see the relevant source code in <i>%matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+desktop/*.m</i>, in case you want to jump ahead and customize your own toolstrip tabs, groups and buttons. In the code snippet below, we first create an empty <code>TabGroup</code>, then add toolstrip tabs into it, and finally add this <code>TabGroup</code> into our ToolGroup using its <i>addTabGroup(hTabGroup)</i> method:</p>
<pre lang="matlab">
% Create a new tab group
%hTabGroup = matlab.ui.internal.desktop.showcaseBuildTabGroup('swing');
hTabGroup = matlab.ui.internal.toolstrip.TabGroup();
hTab1 = matlab.ui.internal.desktop.showcaseBuildTab_Buttons('swing');
hTabGroup.add(hTab1);
%hTabGroup.add(matlab.ui.internal.desktop.showcaseBuildTab_Gallery());
hTabGroup.add(matlab.ui.internal.desktop.showcaseBuildTab_Layout('swing'));
% Select tab #1 (common)
hTabGroup.SelectedTab = hTab1;
% Add the tab group to the built-in toolstrip
hToolGroup.addTabGroup(hTabGroup);
</pre>
<p>We now have an &#8220;App&#8221; that has a toolstrip, but no clients (yet), and a hidden Data Browser side-panel:<br />
<center><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_2a.png" alt='ToolGroup "App" with a simple toolstrip (no clients yet)' title='ToolGroup "App" with a simple toolstrip (no clients yet)' width="80%" style="max-width:673px;" /></center><br />
Now let&#8217;s add some clients (docked figures):</p>
<h3 id="clients">Adding clients (docked figures) to the ToolGroup</h3>
<p>There are two easy variants for adding docked figures in a ToolGroup: The easiest is to use the ToolGroup&#8217;s <i>addFigure(hFigure)</i> method:</p>
<pre lang="matlab">
% Create a figure and dock it into the tool-group
hFig1 = figure('Name','3D');
surf(peaks);
hToolGroup.addFigure(hFig1);
</pre>
<p>The second variant enables to dock a figure that has a specific set of toolstrip tabs attached to it. These tabs will only display in the toolstrip when that particular figure has focus. We do this by creating a new TabGroup (just as we have done above), and then add the figure and TabGroup to the container using the ToolGroup&#8217;s <i>addClientTabGroup(hFigure,hTabGroup)</i> method:</p>
<pre lang="matlab">
% Create the 2nd figure
hFig2 = figure('Name','2D');
plot(rand(5)); drawnow
% Add a few tabs that are only relevant to this specific figure
hTabGroup2 = matlab.ui.internal.toolstrip.TabGroup();
hTab2 = matlab.ui.internal.desktop.showcaseBuildTab_Selections();
hTabGroup2.add(hTab2);
hTabGroup2.add(matlab.ui.internal.desktop.showcaseBuildTab_EditValue());
% Add the figure and tabs to the ToolGroup
hToolGroup.addClientTabGroup(hFig2, hTabGroup2);
</pre>
<p><center><figure style="width: 450px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_2c_animated.gif" alt="ToolGroup with clients and dynamic toolstrip" title="ToolGroup with clients and dynamic toolstrip" width="450" height="314" /><figcaption class="wp-caption-text">ToolGroup with clients and dynamic toolstrip</figcaption></figure></center><br />
In this example, the &#8220;Selection&#8221; and &#8220;Values&#8221; toolstrip tabs only appear when the 2nd figure (&#8220;2D&#8221;) has focus. A similar behavior exists in the Matlab Desktop and Editor, where some tabs are only shown when certain clients have focus.</p>
<h3 id="View">Removing the View tab</h3>
<p>Note that the &#8220;View&#8221; toolstrip tab (which enables setting the appearance of the docked figures: layout, tab positions (top/bottom/left/right), ordering etc.) is automatically added to the toolstrip and always appears last. We can remove this View tab using the ToolGroup&#8217;s <i>hideViewTab()</i> method. The tab will not immediately be removed, only when the toolstrip is repainted, for example, when we switch focus between the docked figures:</p>
<pre lang="matlab">
hToolGroup.hideViewTab;  % toolstrip View tab is still visible at this point
figure(hFig1);  % change focus to hFig1 - toolstrip is repainted without View tab
</pre>
<h3 id="conclusion">Conclusion</h3>
<p>It&#8217;s relatively easy to dock figures into a standalone &#8220;App&#8221; window that has a custom toolstrip, which can even be dynamically modified based on the figure which is currently in focus. Naturally, this has little benefit if we cannot customize the toolstrip components: labels, icons, control type, grouping and most importantly &#8211; callbacks. This topic deserves a dedicated post, which I plan to be the next in this miniseries. Stay tuned &#8211; hopefully the next post will not take me as long to publish as this post (I was quite busy recently)&#8230;</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app">Matlab toolstrip – part 2 (ToolGroup App)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-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-1" rel="bookmark" title="Matlab toolstrip &#8211; part 1">Matlab toolstrip &#8211; part 1 </a> <small>Matlab contains extensive toolstrip (ribbon) functionality that can be integrated in user programs (GUI). ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app/feed</wfw:commentRss>
			<slash:comments>17</slash:comments>
		
		
			</item>
		<item>
		<title>Scrollable GUI panels</title>
		<link>https://undocumentedmatlab.com/articles/scrollable-gui-panels?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scrollable-gui-panels</link>
					<comments>https://undocumentedmatlab.com/articles/scrollable-gui-panels#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 25 Jul 2018 09:50:31 +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[uipanel]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7824</guid>

					<description><![CDATA[<p>Scrollbars can easily be added to Matlab panels, to enable scroll-panes of GUI controls and axes. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/scrollable-gui-panels">Scrollable GUI panels</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/tab-panels-uitab-and-relatives" rel="bookmark" title="Tab panels &#8211; uitab and relatives">Tab panels &#8211; uitab and relatives </a> <small>This article describes several undocumented Matlab functions that support tab-panels...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/syntax-highlighted-labels-panels" rel="bookmark" title="Syntax highlighted labels &amp; panels">Syntax highlighted labels &amp; panels </a> <small>Syntax-highlighted labels and edit-boxes can easily be displayed in Matlab GUI - this article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-matlab-uipanels" rel="bookmark" title="Customizing Matlab uipanels">Customizing Matlab uipanels </a> <small>Matlab uipanel controls can be customized using Java in ways that are impossible with plain Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-uipanels" rel="bookmark" title="Transparent uipanels">Transparent uipanels </a> <small>Matlab uipanels can be made transparent, for very useful effects. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab enables two types of GUI container types, via the <b>Units</b> property: fixed-size (<code>'pixels'</code>, <code>'chars'</code>, etc.) and flexible (<code>'normalized'</code>). In many cases, we need something in between: a panel that expands dynamically when its container grows (i.e., flexible/<code>normalized</code>), and displays scroll-bars when the container shrinks (i.e., fixed size, with a scrollable viewport). This functionality is relatively easy to achieve using a bit of undocumented magic powder. Today&#8217;s post will show how to do this with legacy (Java-based) figures, and next week&#8217;s post will do the same for web-based (JavaScript) uifigures.<br />
<center style="font-size:12px;"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/uipanel_animated.gif" alt="Scrollable Matlab GUI panel" title="Scrollable Matlab GUI panel" width="315" height="315" /><br />
Scrollable Matlab GUI panel</center><span id="more-7824"></span></p>
<h3 id="Description">Technical description</h3>
<p>The basic idea is that in HG2 (Matlab release R2014b onward), <i><b>uipanel</b></i>s are implemented using standard Java <code>JPanel</code> components. This enables all sorts of <a href="https://undocumentedmatlab.com/articles/customizing-matlab-uipanels" target="_blank">interesting customizations</a>. For the purposes of today&#8217;s discussion, the important thing to note is that the underlying <code>JPanel</code> object can be re-parented to reside inside a Java <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html" rel="nofollow" target="_blank">JScrollPanel</a>.<br />
So, the idea is to get the Matlab panel&#8217;s underlying <code>JPanel</code> object reference, then embed it within a new <code>JScrollPanel</code> object that is placed at the exact same GUI coordinates as the original panel. The essential Matlab code snippet is this:</p>
<pre lang="matlab">
% Create the Matlab uipanel in the GUI
hPanel = uipanel(...); drawnow
% Get the panel's underlying JPanel object reference
jPanel = hPanel.JavaFrame.getGUIDEView.getParent;
% Embed the JPanel within a new JScrollPanel object
jScrollPanel = javaObjectEDT(javax.swing.JScrollPane(jPanel));
% Remove the JScrollPane border-line
jScrollPanel.setBorder([]);
% Place the JScrollPanel in same GUI location as the original panel
pixelpos = getpixelposition(hPanel);
hParent = hPanel.Parent;
[hjScrollPanel, hScrollPanel] = javacomponent(jScrollPanel, pixelpos, hParent);
hScrollPanel.Units = 'norm';
% Ensure that the scroll-panel and contained panel have linked visibility
hLink = linkprop([hPanel,hScrollPanel],'Visible');
setappdata(hPanel,'ScrollPanelVisibilityLink',hLink);
</pre>
<p>Note that this code will only work with panels created in legacy figures, not web-based uifigures (as I mentioned above, a similar solution for uifigures will be presented here next week).<br />
Also note that the new scroll-panel is created with <i><b>javaObjectEDT</b></i>, in order to avoid <a href="https://undocumentedmatlab.com/articles/matlab-and-the-event-dispatch-thread-edt" target="_blank">EDT synchronization problems</a><br />
We also want to link the visibility of the scroll-panel and its contained Matlab panel (<code>hPanel</code>), so that when the panel is set to be non-visible (<code>hPanel.Visible='off'</code>), the entire scroll-panel (scrollbars included) will become invisible, and vice-versa. We can do this by linking the <b>Visible</b> property of the Matlab panel and the scroll-panel container (<code>hScrollPanel</code>) using the <i><b>linkprop</b></i> function at the bottom of the script above. Note that we must persist the resulting <code>hLink</code> otherwise it becomes defunct &#8211; this is done by using <i><b>setappdata</b></i> to store the link in the panel (this way, when the panel is deleted, so does the link).</p>
<h3 id="Resize">Resizing the container</h3>
<p>The scroll-panel is created with a specific <code>pixelpos</code> location and size, and then its container is made to have <code>normalized</code> units. This ensures that when the container (<code>hParent</code>) grows, the scroll-panel grows as well, and no scrollbars appear (since they are not needed). But when the container shrinks in the X and/or Y direction, corresponding scrollbars appear as-needed. It sounds complicated, but it&#8217;s actually very intuitive, as the animated image above shows.<br />
When the container resizes, the displayed viewport image may &#8220;jump&#8221; sideways. To fix this we can attach a simple repaint callback function to the scroll-panel&#8217;s <b>SizeChangedFcn</b> property:</p>
<pre lang="matlab">
% Attach a repaint callback function
hScrollPanel.SizeChangedFcn = @repaintScrollPane;
% Define the callback function:
function repaintScrollPane(hScrollPanel, varargin)
    drawnow
    jScrollPanel = hScrollPanel.JavaPeer;
    offsetX = 0; %or: jScrollPanel.getHorizontalScrollBar.getValue;
    offsetY = 0; %or: jScrollPanel.getVerticalScrollBar.getValue;
    jOffsetPoint = java.awt.Point(offsetX, offsetY);
    jViewport = jScrollPanel.getViewport;
    jViewport.setViewPosition(jOffsetPoint);
    jScrollPanel.repaint;
end
</pre>
<p><center><figure style="width: 315px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/uipanel4b_cropped.gif" alt="Scrollbars automatically appear as-needed during resize" title="Scrollbars automatically appear as-needed during resize" width="315" height="183" /><figcaption class="wp-caption-text">Scrollbars automatically appear as-needed during resize</figcaption></figure></center></p>
<h3 id="ViewOffset">Viewport position/offset</h3>
<p>It would be convenient to have an easy-to-use <b>ViewOffset</b> property in the <code>hScrollPanel</code> object, in order to be able to programmatically query and set the current viewport position (i.e., scrollbars offset). We can add this property via the <i><b>addprop</b></i> function:</p>
<pre lang="matlab">
% Add a new Viewoffset property to hSCrollPanel object
hProp = addprop(hScrollPanel, 'ViewOffset');
hProp.GetMethod = @getViewOffset;  %viewOffset = getViewOffset(hScrollPanel)
hProp.SetMethod = @setViewOffset;  %setViewOffset(hScrollPanel, viewOffset)
% Getter method for the dynamic ViewOffset property
function viewOffset = getViewOffset(hScrollPanel, varargin)
    jScrollPanel = hScrollPanel.JavaPeer;
    jPoint = jScrollPanel.getViewport.getViewPosition;
    viewOffset = [jPoint.getX, jPoint.getY];
end
% Setter method for the dynamic ViewOffset property
function setViewOffset(hScrollPanel, viewOffset)
    jPoint = java.awt.Point(viewOffset(1), viewOffset(2));
    jScrollPanel = hScrollPanel.JavaPeer;
    jScrollPanel.getViewport.setViewPosition(jPoint);
    jScrollPanel.repaint;
end
</pre>
<p>This enables us to both query and update the scroll-panel&#8217;s view position &#8211; <code>[0,0]</code> means top-left corner (i.e., no scroll); <code>[12,34]</code> mean scrolling 12 to the right and 34 down:</p>
<pre lang="matlab">
>> offset = hScrollPanel.ViewOffset   % or: get(hScrollPanel,'ViewOffset')
offset =
     0     0
>> offset = hScrollPanel.ViewOffset   % or: get(hScrollPanel,'ViewOffset')
offset =
    12    34
% Scroll 30 pixels right, 50 pixels down
>> hScrollPanel.ViewOffset = [30,50];   % or: set(hScrollPanel,'ViewOffset',[30,50])
</pre>
<h3 id="attachScrollPanelTo">attachScrollPanelTo utility</h3>
<p>I have prepared a utility called <i><b>attachScrollPanelTo</b></i> (<a href="https://www.mathworks.com/matlabcentral/fileexchange/68325-attachscrollpanelto-add-scroll-panel-to-a-uipanel-or-axes" rel="nofollow" target="_blank">downloadable from the Matlab File Exchange</a>), which encapsulates all of the above, plus a few other features: inputs validation, <b>Viewport</b> property in the output scroll-pane object, automatic encasing in a new panel for input object that are not already a panel, etc. Feel free to download the utility, use it in your program, and modify the source-code to fit your needs. Here are some usage examples:</p>
<pre lang="matlab">
attachScrollPanelTo();  % display the demo
attachScrollPanelTo(hPanel) % place the specified hPanel in a scroll-panel
hScroll = attachScrollPanelTo(hPanel);
hScroll.ViewOffset = [30,50];  % set viewport offset (30px right, 50px down)
set(hScroll, 'ViewOffset',[30,50]);  % equivalent alternative
</pre>
<p>If you&#8217;d like me to add flare to your Matlab GUI, don&#8217;t hesitate to contact me on my <a href="https://undocumentedmatlab.com/consulting" target="_blank">Consulting page</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/scrollable-gui-panels">Scrollable GUI panels</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/tab-panels-uitab-and-relatives" rel="bookmark" title="Tab panels &#8211; uitab and relatives">Tab panels &#8211; uitab and relatives </a> <small>This article describes several undocumented Matlab functions that support tab-panels...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/syntax-highlighted-labels-panels" rel="bookmark" title="Syntax highlighted labels &amp; panels">Syntax highlighted labels &amp; panels </a> <small>Syntax-highlighted labels and edit-boxes can easily be displayed in Matlab GUI - this article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-matlab-uipanels" rel="bookmark" title="Customizing Matlab uipanels">Customizing Matlab uipanels </a> <small>Matlab uipanel controls can be customized using Java in ways that are impossible with plain Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-uipanels" rel="bookmark" title="Transparent uipanels">Transparent uipanels </a> <small>Matlab uipanels can be made transparent, for very useful effects. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/scrollable-gui-panels/feed</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Blocked wait with timeout for asynchronous events</title>
		<link>https://undocumentedmatlab.com/articles/blocked-wait-with-timeout-for-asynchronous-events?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=blocked-wait-with-timeout-for-asynchronous-events</link>
					<comments>https://undocumentedmatlab.com/articles/blocked-wait-with-timeout-for-asynchronous-events#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 13 May 2018 20:22:08 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Listeners]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Memory]]></category>
		<category><![CDATA[Performance]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7620</guid>

					<description><![CDATA[<p>It is easy to convert asynchronous (streaming) events into a blocked wait in Matlab. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/blocked-wait-with-timeout-for-asynchronous-events">Blocked wait with timeout for asynchronous events</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/waiting-for-asynchronous-events" rel="bookmark" title="Waiting for asynchronous events">Waiting for asynchronous events </a> <small>The Matlab waitfor function can be used to wait for asynchronous Java/ActiveX events, as well as with timeouts. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-events-and-listeners" rel="bookmark" title="UDD Events and Listeners">UDD Events and Listeners </a> <small>UDD event listeners can be used to listen to property value changes and other important events of Matlab objects...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events" rel="bookmark" title="Matlab callbacks for Java events">Matlab callbacks for Java events </a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/detecting-window-focus-events" rel="bookmark" title="Detecting window focus events">Detecting window focus events </a> <small>Matlab does not have any documented method to detect window focus events (gain/loss). This article describes an undocumented way to detect such events....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Readers of this website may have noticed that I have recently added an <a href="/iqml" rel="nofollow" target="_blank">IQML section</a> to the website&#8217;s top menu bar. IQML is a software connector that connects Matlab to DTN&#8217;s IQFeed, a financial data-feed of live and historic market data. IQFeed, like most other data-feed providers, sends its data in asynchronous messages, which need to be processed one at a time by the receiving client program (Matlab in this case). I wanted IQML to provide users with two complementary modes of operation:<br />
<span class="alignright"><a href="/iqml" rel="nofollow" target="_blank"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/IQML.png" title="IQML's IQFeed-Matlab connectivity" alt="IQML's IQFeed-Matlab connectivity" width="426" height="213"/></a></span></p>
<ul>
<li><b>Streaming</b> (asynchronous, non-blocking) &#8211; incoming server data is processed by internal callback functions in the background, and is made available for the user to query at any later time.</li>
<li><b>Blocking</b> (synchronously waiting for data) &#8211; in this case, the main Matlab processing flows waits until the data arrives, or until the specified timeout period has passed &#8211; whichever comes first.</li>
</ul>
<p>Implementing streaming mode is relatively simple in general &#8211; all we need to do is ensure that the underlying connector object passes the incoming server messages to the relevant Matlab function for processing, and ensure that the user has some external way to access this processed data in Matlab memory (in practice making the connector object pass incoming data messages as Matlab callback events may be non-trivial, but that&#8217;s a separate matter &#8211; <a href="/articles/matlab-callbacks-for-java-events" target="_blank">read here</a> for details).<br />
In today&#8217;s article I&#8217;ll explain how we can implement a blocking mode in Matlab. It may sound difficult but it turns out to be relatively simple.<br />
I had several requirements/criteria for my blocked-wait implementation:</p>
<ol>
<li><b>Compatibility</b> &#8211; It had to work on all Matlab platforms, and all Matlab releases in the past decade (which rules out using Microsoft Dot-NET objects)</li>
<li><b>Ease-of-use</b> &#8211; It had to work out-of-the-box, with no additional installation/configuration (which ruled out using Perl/Python objects), and had to use a simple interface function</li>
<li><b>Timeout</b> &#8211; It had to implement a timed-wait, and had to be able to tell whether the program proceeded due to a timeout, or because the expected event has arrived</li>
<li><b>Performance</b> &#8211; It had to have minimal performance overhead</li>
</ol>
<p><span id="more-7620"></span></p>
<h3 id="basic">The basic idea</h3>
<p>The basic idea is to use Matlab&#8217;s builtin <i><b>waitfor</b></i>, as I explained in <a href="/articles/waiting-for-asynchronous-events" target="_blank">another post</a> back in 2012. If our underlying connector object has some settable boolean property (e.g., <code>Done</code>) then we can set this property in our event callback, and then <code>waitfor(object,'Done')</code>. The timeout mechanism is implemented using a dedicated timer object, as follows:</p>
<pre lang="matlab">
% Wait for data updates to complete (isDone = false if timeout, true if event has arrived)
function isDone = waitForDone(object, timeout)
    % Initialize: timeout flag = false
    object.setDone(false);
    % Create and start the separate timeout timer thread
    hTimer = timer('TimerFcn',@(h,e)object.setDone(true), 'StartDelay',timeout);
    start(hTimer);
    % Wait for the object property to change or for timeout, whichever comes first
    waitfor(object,'Done');
    % waitfor is over - either because of timeout or because the data changed
    % To determine which, check whether the timer callback was activated
    isDone = isvalid(hTimer) && hTimer.TasksExecuted == 0;
    % Delete the timer object
    try stop(hTimer);   catch, end
    try delete(hTimer); catch, end
    % Return the flag indicating whether or not timeout was reached
end  % waitForDone
</pre>
<p>where the event callback is responsible for invoking <code>object.setDone(true)</code> when the server data arrives. The usage would then be similar to this:</p>
<pre lang="matlab">
requestDataFromServer();
if isBlockingMode
   % Blocking mode - wait for data or timeout (whichever comes first)
   isDone = waitForDone(object, 10.0);  % wait up to 10 secs for data to arrive
   if ~isDone  % indicates a timeout
      fprintf(2, 'No server data has arrived within the specified timeout period!\n')
   end
else
   % Non-blocking (streaming) mode - continue with regular processing
end
</pre>
<h3 id="generic">Using a stand-alone generic signaling object</h3>
<p>But what can we do if we don&#8217;t have such a <code>Done</code> property in our underlying object, or if we do not have programmatic access to it?<br />
We could create a new non-visible figure and then <i><b>waitfor</b></i> one of its properties (e.g. <code>Resize</code>). The property would be initialized to <code>'off'</code>, and within both the event and timer callbacks we would set it to <code>'on'</code>, and then <code>waitfor(hFigure,'Resize','on')</code>. However, figures, even if non-visible, are quite heavy objects in terms of both memory, UI resources, and performance.<br />
It would be preferable to use a much lighter-weight object, as long as it abides by the other criteria above. Luckily, there are numerous such objects in Java, which is bundled in every Matlab since 2000, on every Matlab platform. As long as we choose a small Java object that has existed forever, we should be fine. For example, we could use a simple <code>javax.swing.JButton</code> and its boolean property <code>Enabled</code>:</p>
<pre lang="matlab">
hSemaphore = handle(javax.swing.JButton);  % waitfor() expects a handle() object, not a "naked" Java reference
% Wait for data updates to complete (isDone = false if timeout, true if event has arrived)
function isDone = waitForDone(hSemaphore, timeout)
    % Initialize: timeout flag = false
    hSemaphore.setEnabled(false);
    % Create and start the separate timeout timer thread
    hTimer = timer('TimerFcn',@(h,e)hSemaphore.setEnabled(true), 'StartDelay',timeout);
    start(hTimer);
    % Wait for the object property to change or for timeout, whichever comes first
    waitfor(hSemaphore,'Enabled');
    % waitfor is over - either because of timeout or because the data changed
    % To determine which, check whether the timer callback was activated
    isDone = isvalid(hTimer) && hTimer.TasksExecuted == 0;
    % Delete the timer object
    try stop(hTimer);   catch, end
    try delete(hTimer); catch, end
    % Return the flag indicating whether or not timeout was reached
end  % waitForDone
</pre>
<p>In this implementation, we would need to pass the <code>hSemaphore</code> object handle to the event callback, so that it would be able to invoke <code>hSemaphore.setEnabled(true)</code> when the server data has arrived.<br />
Under the hood, note that <code>Enabled</code> is not a true &#8220;property&#8221; of <code>javax.swing.JButton</code>, but rather exposes two simple public getter/setter methods (<i>setEnabled()</i> and <i>isEnabled()</i>), which Matlab interprets as a &#8220;property&#8221;. For all intents and purposes, in our Matlab code we can treat <code>Enabled</code> as a property of <code>javax.swing.JButton</code>, including its use by Matlab&#8217;s builtin <i><b>waitfor</b></i> function.<br />
There is a light overhead to this: on my laptop the <i><b>waitfor</b></i> function returns ~20 mSecs after the invocation of <code>hSemaphore.setEnabled(true)</code> in the timer or event callback &#8211; in many cases this overhead is negligible compared to the networking latencies for the blocked data request. When event reactivity is of utmost importance, users can always use streaming (non-blocking) mode, and process the incoming data events immediately in a callback.<br />
Of course, it would have been best if MathWorks would add a timeout option and return value to Matlab&#8217;s builtin <i><b>waitfor</b></i> function, similar to my <code>waitForDone</code> function &#8211; this would significantly simplify the code above. But until this happens, you can use <code>waitForDone</code> pretty-much as-is. I have used similar combinations of blocking and streaming modes with multiple other connectors that I implemented over the years (Interactive Brokers, CQG, Bloomberg and Reuters for example), and the bottom line is that it actually works well in practice.<br />
<a href="/consulting" target="_blank">Let me know</a> if you&#8217;d like me to assist with your own Matlab project or data connector, either developing it from scratch or improving your existing code. I will be visiting Boston and New York in early June and would be happy to meet you in person to discuss your specific needs.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/blocked-wait-with-timeout-for-asynchronous-events">Blocked wait with timeout for asynchronous events</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/waiting-for-asynchronous-events" rel="bookmark" title="Waiting for asynchronous events">Waiting for asynchronous events </a> <small>The Matlab waitfor function can be used to wait for asynchronous Java/ActiveX events, as well as with timeouts. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-events-and-listeners" rel="bookmark" title="UDD Events and Listeners">UDD Events and Listeners </a> <small>UDD event listeners can be used to listen to property value changes and other important events of Matlab objects...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events" rel="bookmark" title="Matlab callbacks for Java events">Matlab callbacks for Java events </a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/detecting-window-focus-events" rel="bookmark" title="Detecting window focus events">Detecting window focus events </a> <small>Matlab does not have any documented method to detect window focus events (gain/loss). This article describes an undocumented way to detect such events....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/blocked-wait-with-timeout-for-asynchronous-events/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Spicing up the Matlab Editor</title>
		<link>https://undocumentedmatlab.com/articles/spicing-up-the-matlab-editor?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=spicing-up-the-matlab-editor</link>
					<comments>https://undocumentedmatlab.com/articles/spicing-up-the-matlab-editor#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 29 Mar 2018 21:34:20 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Andreas Justin]]></category>
		<category><![CDATA[Editor]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7472</guid>

					<description><![CDATA[<p>Matlab's Editor and Workspace can be enhanced quite significantly using an open-source utility. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/spicing-up-the-matlab-editor">Spicing up the Matlab Editor</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/editormacro-assign-a-keyboard-macro-in-the-matlab-editor" rel="bookmark" title="EditorMacro &#8211; assign a keyboard macro in the Matlab editor">EditorMacro &#8211; assign a keyboard macro in the Matlab editor </a> <small>EditorMacro is a new utility that enables setting keyboard macros in the Matlab editor. this post details its inner workings....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/accessing-the-matlab-editor" rel="bookmark" title="Accessing the Matlab Editor">Accessing the Matlab Editor </a> <small>The Matlab Editor can be accessed programmatically, for a wide variety of possible uses - this article shows how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/non-textual-editor-actions" rel="bookmark" title="Non-textual editor actions">Non-textual editor actions </a> <small>The UIINSPECT utility can be used to expand EditorMacro capabilities to non-text-insertion actions. This is how:...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/recovering-previous-editor-state" rel="bookmark" title="Recovering previous editor state">Recovering previous editor state </a> <small>Recovering the previous state of the Matlab editor and its loaded documents is possible using a built-in backup config file. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I&#8217;d like to introduce guest blogger <a href="https://github.com/GavriYashar" rel="nofollow" target="_blank">Andreas Justin</a>, who will discuss some way-cool features in his Editor Plugin utility. Many of his feature implementations are not Editor-specific and can be reused in other Matlab-Desktop applications, for example dockable panels, and integration with Matlab&#8217;s main Preferences window.</i><br />
<i><b><u>Note</u>: I will be traveling to the USA in June, and to Spain in August. If you would like me to visit your location for onsite consulting or training, then please let me know.</b></i><br />
<i>Happy Easter/Passover!</i></p>
<h3 id="overview">Overview</h3>
<p><figure style="width: 128px" class="wp-caption alignright"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin3.gif" alt="Editor-plugin's cool logo" title="Editor-plugin's cool logo" width="128" height="128" /><figcaption class="wp-caption-text">Editor-plugin's cool logo</figcaption></figure>Compared to other IDE like IntellIJ, Eclipse and many more, Matlab&#8217;s editor seems somewhat outdated. Especially writing Object-Oriented code in Matlab is kind of a hassle. To make Matlab more user friendly, I&#8217;ve written a Java app that adds important features to the editor &#8211; Features such as navigating inside Class-code and in Inherited members; Searching through methods and instantly jumping to desired location; Reopening an editor that was closed by accident; Storing bookmarks between Matlab sessions; and Live Templates using commands directly written in the editor, replaced by pre-defined text.</p>
<p>The default Keyboard shortcuts listed below for the features can be customized. Most variables can be customized as well (I will point out which variables are not [yet] customizable).<br />
Most GUIs have a search field. Within this search field you can move the list or the tree up and down using arrow keys, or hit &lt;escape&gt; to return to editor. These search fields allow you to enter regular expressions to limit results shown in list or tree. Also, most GUIs are dockable.<br />
The Editor-Plugin utility is open-source. It is available <a href="https://github.com/GavriYashar/Matlab-Editor-Plugin" rel="nofollow" target="_blank">on GitHub</a> and also mirrored <a href="https://www.mathworks.com/matlabcentral/fileexchange/58497-gavriyashar-matlab-editor-plugin" rel="nofollow" target="_blank">on the Matlab File Exchange</a>. A <a href="https://github.com/GavriYashar/Matlab-Editor-Plugin/wiki/Setup" rel="nofollow" target="_blank">detailed setup guide</a> is provided on the utility&#8217;s <a href="https://github.com/GavriYashar/Matlab-Editor-Plugin/wiki" rel="nofollow" target="_blank">wiki section in GitHub</a>.<br />
If you discover any problem or have any suggestion for improvement, please visit the utility&#8217;s <a href="https://github.com/GavriYashar/Matlab-Editor-Plugin/issues" rel="nofollow" target="_blank">Issues section on GitHub</a>, where all open/closed issues can be tracked and discussed.<br />
A brief overview of some of the features is presented below. For a detailed explanation of these and other features (which are not listed below), please review the <a href="https://github.com/GavriYashar/Matlab-Editor-Plugin/wiki/Features" rel="nofollow" target="_blank">Features section</a> of the utility&#8217;s wiki (you guessed it: on GitHub&#8230;).</p>
<style type="text/css" media="screen">
kbd {
    display: inline-block;
    padding: 3px 5px;
    font-size: 11px;
    line-height: 10px;
    color: #444d56;
    vertical-align: middle;
    background-color: #fafbfc;
    border: solid 1px #c6cbd1;
    border-bottom-color: #959da5;
    border-radius: 3px;
    box-shadow: inset 0 -1px 0 #959da5;
}
</style>
<h3 id="editing">Editing</h3>
<ul>
<li><b>Delete / duplicate lines</b> &#8211; <kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>Y</kbd> or <kbd>D</kbd> allows you to delete or duplicate current line.<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin1.gif" alt="Deleting/duplicating complete lines" title="Deleting/duplicating complete lines" width="90%" style="max-width:778px;"/></center></li>
<li><b>Move lines up or down</b> &#8211; <kbd>CTRL</kbd> + <kbd>ALT</kbd> + <kbd>UP</kbd> or <kbd>DOWN</kbd> allows you to move selected lines up or down.<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin10.gif" alt="Moving complete lines" title="Moving complete lines" width="90%" style="max-width:750px;"/></center></li>
<li><b>Live (auto-replace) templates</b> &#8211; Live Templates are editor commands you can design to insert predefined code. Here&#8217;s an example for the command <code>%this%</code> (delivered within the package). When you type a command into the editor the string will get replaced by the predefined text. This predefined text may include variables depending on what you want to achieve. <code>%this%</code> was designed to insert the fully qualified name of the current class you&#8217;re in (or function, or script).<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin9.gif" alt="Auto-replace template" title="Auto-replace templates" width="90%" style="max-width:647px;"/></center></li>
<li><b>Clipboard Stack</b> &#8211; <kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>V</kbd> opens the Clipboard Stack, where the last 10 copied/cut text are stored and can be directly inserted into the current editor position. The Clipboard Stack only stores text copied from editor.</li>
</ul>
<p><span id="more-7472"></span></p>
<h3 id="navigation">Navigation</h3>
<ul>
<li><b>Auto switch current folder and detail viewer</b> &#8211; Switching editor tabs will update the Desktop&#8217;s current folder and detail viewer. This behavior can be directly changed in the detail viewer bar.<br />
Use the new icons in the Desktop&#8217;s Current Folder panel: <img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin8.png" alt="Toggle detail viewer" title="Toggle detail viewer" width="16" height="16"/> to toggle detail viewer and <img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin2.png" alt="Toggle following the current editor file" title="Toggle following the current editor file" width="16" height="16"/> to toggle following the current editor file.<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin6.gif" alt="Follow current editor file" title="Follow current editor file" width="90%" style="max-width:574px;"/></center></li>
<li><b>File Structure</b> &#8211; I personally use this one the most: <kbd>CTRL</kbd> + <kbd>F12</kbd> will show a GUI that let you search methods and properties including inherited ones.<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin7.gif" alt="File structure analysis" title="File structure analysis" width="90%" style="max-width:803px;"/></center></li>
<li><b>Navigation History</b> &#8211; Every editor file that is opened is stored in the navigation history. Up to 50 editor file paths are stored. If you have a 5-Button Mouse, you can navigate through previous location (backward and forward).</li>
<li><b>Recently Closed</b> &#8211; <kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>T</kbd> will show a GUI that allows you to reopen closed editors this or last session.</li>
<li><b>Bookmarks</b> &#8211; <kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>F2</kbd> will show a GUI that allows you to name, search and delete bookmarks. Matlab has this nice feature to delete bookmarks after closing the editor. This feature will store all bookmarks. If an editor or Matlab is closed and opened later. All Bookmarks will be restored.<br />
This feature has some issues though. The most obvious first: if the source file has been changed outside of Matlab, the bookmark does not get updated, and may point to the wrong line, or gets deleted. Also on some Systems the default shortcut does not work. But there are workarounds.</li>
</ul>
<h3 id="others">Other useful features</h3>
<ul>
<li><b>Dockable Windows</b> &#8211; As mentioned before, most GUIs are dockable.<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin5.gif" alt="Dockable Windows" title="Dockable Windows" width="90%" style="max-width:820px;"/></center></li>
<li><b>Preferences</b> &#8211; Preferences panel integrated in Matlab&#8217;s main Preferences window.<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin-preferences.png" alt="Preferences panel integrated in Matlab's main Preferences window" title="Preferences panel integrated in Matlab's main Preferences window" width="90%" style="max-width:912px;"/></center></li>
<li><b>Execute current line</b> &#8211; <kbd>SHIFT</kbd> + <kbd>F9</kbd> allows you to execute the current line. This is equivalent to selecting the entire line, then clicking <kbd>F9</kbd>, and is similar in concept to the editor&#8217;s built-in ability to execute the current cell-block.<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin4.gif" alt="Execute current line" title="Execute current line" width="90%" style="max-width:795px;"/></center></li>
<li><b>VarDiff</b> &#8211; Select two variables in the workspace and compare them using Matlab&#8217;s internal comparison feature (adding a custom hook to the Workspace context-menu was <a href="/articles/customizing-workspace-context-menu" target="_blank">discussed by Yair</a> back in 2010).<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin-Vardiff_context.png" alt="Variables comparison integrated in the Workspace browser" title="Variables comparison integrated in the Workspace browser" width="90%" style="max-width:392px;"/></center></li>
<li><b>KeyPressListener</b> &#8211; Allows you to create custom keyboard shortcuts for your own functions. A similar functionality was <a href="/articles/editormacro-assign-a-keyboard-macro-in-the-matlab-editor" target="_blank">discussed by Yair</a> back in 2009.</li>
</ul>
<p>As noted above, a detailed explanation of these and other features is provided in the <a href="https://github.com/GavriYashar/Matlab-Editor-Plugin/wiki/Features" rel="nofollow" target="_blank">Features section</a> of the utility&#8217;s wiki. If you discover any problem or have any suggestion for improvement, please visit the utility&#8217;s <a href="https://github.com/GavriYashar/Matlab-Editor-Plugin/issues" rel="nofollow" target="_blank">Issues section on GitHub</a>, where issues can be tracked and discussed.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/spicing-up-the-matlab-editor">Spicing up the Matlab Editor</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/editormacro-assign-a-keyboard-macro-in-the-matlab-editor" rel="bookmark" title="EditorMacro &#8211; assign a keyboard macro in the Matlab editor">EditorMacro &#8211; assign a keyboard macro in the Matlab editor </a> <small>EditorMacro is a new utility that enables setting keyboard macros in the Matlab editor. this post details its inner workings....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/accessing-the-matlab-editor" rel="bookmark" title="Accessing the Matlab Editor">Accessing the Matlab Editor </a> <small>The Matlab Editor can be accessed programmatically, for a wide variety of possible uses - this article shows how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/non-textual-editor-actions" rel="bookmark" title="Non-textual editor actions">Non-textual editor actions </a> <small>The UIINSPECT utility can be used to expand EditorMacro capabilities to non-text-insertion actions. This is how:...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/recovering-previous-editor-state" rel="bookmark" title="Recovering previous editor state">Recovering previous editor state </a> <small>Recovering the previous state of the Matlab editor and its loaded documents is possible using a built-in backup config file. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/spicing-up-the-matlab-editor/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Adding custom properties to GUI objects</title>
		<link>https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=adding-custom-properties-to-gui-objects</link>
					<comments>https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 15 Feb 2018 12:39:35 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[schema.prop]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7324</guid>

					<description><![CDATA[<p>It is very easy to add custom user-defined properties and methods to GUI handles and Java references in Matlab. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects">Adding custom properties to GUI objects</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/adding-dynamic-properties-to-graphic-handles" rel="bookmark" title="Adding dynamic properties to graphic handles">Adding dynamic properties to graphic handles </a> <small>It is easy and very useful to attach dynamic properties to Matlab graphics objects in run-time. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/borderless-button-used-for-plot-properties" rel="bookmark" title="Borderless button used for plot properties">Borderless button used for plot properties </a> <small>A borderless button can be used to add unobtrusive functionality to plot axes...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-properties" rel="bookmark" title="UDD Properties">UDD Properties </a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab objects have numerous built-in properties (some of them publicly-accessible/documented and others not, but that&#8217;s a different story). For various purposes, it is sometimes useful to attach custom user-defined properties to such objects. While there was never a fully-documented way to do this, most users simply attached such properties as fields in the <b>UserData</b> property or the object&#8217;s [hidden] <b>ApplicationData</b> property (accessible via the documented <i><b>setappdata</b></i>/<i><b>getappdata</b></i> functions).<br />
An undocumented way to attach actual new user-defined properties to objects such as GUI handles or Java references has historically (in HG1, up to R2014a) been to use the undocumented <i><b>schema.prop</b></i> function, as I <a href="/articles/adding-dynamic-properties-to-graphic-handles" target="_blank">explained here</a>. As I wrote in that post, in HG2 (R2014b onward), we can use the fully-documented <a href="https://www.mathworks.com/help/matlab/ref/dynamicprops.addprop.html" rel="nofollow" target="_blank"><i><b>addprop</b></i> function</a> to add new custom properties (and methods) to such objects. What is still NOT documented, as far as I could tell, is that all of Matlab&#8217;s builtin handle graphics objects indirectly inherit the <code>dynamicprops</code> class, which allows this. The bottom line is that we can dynamically add custom properties in run-time to any HG object, without affecting any other object. In other words, the new properties will only be added to the handles that we specifically request, and not to any others.<br />
All this is important, because for some unexplained reason that escapes my understanding, MathWorks chose to seal its classes, thus preventing users to extend them with sub-classes that contain the new properties. So much frustration could have been solved if MathWorks would simply remove the <b>Sealed</b> class meta-property from its classes. Then again, I&#8217;d have less to blog about in that case&#8230;<br />
Anyway, why am I rehashing old news that I have already reported a few years ago?<br />
Well, first, because my experience has been that this little tidbit is [still] fairly unknown by Matlab developers. Secondly, I happened to run into a perfect usage example a short while ago that called for this solution: a <a href="https://stackoverflow.com/questions/48597836/matlab-figure-age" rel="nofollow" target="_blank">StackExchange user asked</a> whether it is possible to tell a GUI figure&#8217;s age, in other words the elapsed time since the figure was created. The simple answer would be to use <i><b>setappdata</b></i> with the creation date whenever we create a figure. However, a &#8220;cleaner&#8221; approach seems to be to create new read-only properties for the figure&#8217;s <b>CreationTime</b> and <b>Age</b>:<br />
<span id="more-7324"></span><br />
First, create a small Matlab function as follows, that attaches the CreationTime property to a figure:</p>
<pre lang="matlab">
function setCreationTime(hFig,varargin)
   hProp = addprop(hFig,'CreationTime');
   hFig.CreationTime = now;
   hProp.SetAccess = 'private';  % make property read-only after setting its initial value
   hProp = addprop(hFig,'Age');
   hProp.GetMethod = @(h,e) etime(datevec(hFig.CreationTime), clock);  % compute on-the-fly
   hProp.SetAccess = 'private';  % make property read-only
end
</pre>
<p>Now assign this function as the default CreateFcn callback function for all new figures from now on:</p>
<pre lang="matlab">
set(0,'DefaultFigureCreateFcn',@setCreationTime)
</pre>
<p>That&#8217;s it &#8211; you&#8217;re done! Whenever a new figure will be created from now on, it will have two custom read-only properties: <b>CreationTime</b> and <b>Age</b>.<br />
For example:</p>
<pre lang="matlab">
>> newFig = figure;
>> newFig.CreationTime
ans =
      737096.613706748
>> ageInDays = now - newFig.CreationTime
ageInDays =
       0.0162507836846635
>> ageDuration = duration(ageInDays*24,0,0)
ageDuration =
  duration
   00:23:24
>> ageString = datestr(ageInDays, 'HH:MM:SS.FFF')
ageString =
    '00:23:24.068'
>> ageInSecs = newFig.Age
ageInSecs =
       1404.06771035492
</pre>
<p>Note that an alternative way to set the computed property <b>Age</b> would have been to set its value to be an anonymous function, but this would have necessitated invoking it with parenthesis (as in: <code>ageInSecs = newFig.Age()</code>). By setting the property&#8217;s <b>GetMethod</b> meta-property we avoid this need.<br />
Keen readers will have noticed that the mechanism that I outlined above for the <b>Age</b> property/method can also be used to add custom user methods. For example, we can create a new custom property named <b>refresh</b> that would be read-only and have a <b>GetMethod</b> which is the function handle of the function that refreshes the object in some way.<br />
Do you have any special uses for custom user-defined properties/methods in your program? or perhaps you have a use-case that might show MathWorks why sub-classing the built-in classes might improve your work? if so, then please place a comment about it below. If enough users show MathWorks why this is important, then maybe it will be fixed in some future release.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects">Adding custom properties to GUI objects</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/adding-dynamic-properties-to-graphic-handles" rel="bookmark" title="Adding dynamic properties to graphic handles">Adding dynamic properties to graphic handles </a> <small>It is easy and very useful to attach dynamic properties to Matlab graphics objects in run-time. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/borderless-button-used-for-plot-properties" rel="bookmark" title="Borderless button used for plot properties">Borderless button used for plot properties </a> <small>A borderless button can be used to add unobtrusive functionality to plot axes...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-properties" rel="bookmark" title="UDD Properties">UDD Properties </a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>IP address input control</title>
		<link>https://undocumentedmatlab.com/articles/ip-address-input-control?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=ip-address-input-control</link>
					<comments>https://undocumentedmatlab.com/articles/ip-address-input-control#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 31 Jan 2018 16:16:12 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[JIDE]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7313</guid>

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

					<description><![CDATA[<p>GUI toolbar button labels can easily be set and customized using underlying Java components. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/toolbar-button-labels">Toolbar button labels</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-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>
<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/adding-a-search-box-to-figure-toolbar" rel="bookmark" title="Adding a search box to figure toolbar">Adding a search box to figure toolbar </a> <small>An interactive search-box can easily be added to a Matlab figure toolbar for enhanced user experience. ...</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>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>I was recently asked by a client to add a few buttons labeled &#8220;1&#8221;-&#8220;4&#8221; to a GUI toolbar. I thought: How hard could that be? Simply <a href="/articles/figure-toolbar-components" target="_blank">get the toolbar&#8217;s handle from the figure</a>, then use the builtin <i><b>uipushtool</b></i> function to add a new button, specifying the label in the <b>String</b> property, right?<br />
<center><img decoding="async" src="https://undocumentedmatlab.com/images/toolbar_labels.png" alt="Labeled toolbar buttons" title="Labeled toolbar buttons" width="80%" style="max-width:612px;" height="140" /></center><br />
Well, not so fast it seems:</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;">hToolbar = findall<span style="color: #080;">(</span>hFig, <span style="color:#A020F0;">'tag'</span>,<span style="color:#A020F0;">'FigureToolBar'</span><span style="color: #080;">)</span>;  <span style="color: #228B22;">% get the figure's toolbar handle</span>
uipushtool<span style="color: #080;">(</span>hToolbar, <span style="color:#A020F0;">'String'</span>,<span style="color:#A020F0;">'1'</span><span style="color: #080;">)</span>;               <span style="color: #228B22;">% add a pushbutton to the toolbar</span>
<span style="color: #FF0000;">Error using <u>uipushtool</u>
There is no String property on the PushTool class. </pre>
</div>
</div>
<p>Apparently, for some unknown reason, standard Matlab only enables us to set the icon (<b>CData</b>) of a toolbar control, but not a text label.<br />
Once again, Java to the rescue: <span id="more-7270"></span><br />
We first get the Java toolbar reference handle, then add the button in standard Matlab (using <i><b>uipushtool</b></i>, <i><b>uitoggletool</b></i> and their kin). We can now access the Java toolbar&#8217;s last component, relying on the fact that Matlab always adds new buttons at the end of the toolbar. Note that we need to use a short <i><b>drawnow</b></i> to ensure that the toolbar is fully re-rendered, otherwise we&#8217;d get an invalid Java handle. Finally, once we have this reference handle to the underlying Java button component, we can set and customize its label text and appearance (font face, border, size, alignment etc.):</p>
<pre lang="matlab">
hToolbar = findall(hFig, 'tag','FigureToolBar');     % get the figure's toolbar handle
jToolbar = hToolbar.JavaContainer.getComponentPeer;  % get the toolbar's Java handle
for buttonIdx = 1 : 4
    % First create the toolbar button using standard Matlab code
    label = num2str(buttonIdx);  % create a string label
    uipushtool(hToolbar, 'ClickedCallback',{@myCallback,analysisIdx}, 'TooltipString',['Run analysis #' label]);
    % Get the Java reference handle to the newly-created button
    drawnow; pause(0.01);  % allow the GUI time to re-render the toolbar
    jButton = jToolbar.getComponent(jToolbar.getComponentCount-1);
    % Set the button's label
    jButton.setText(label)
end
</pre>
<p>The standard Matlab toolbar button size (23&#215;23 pixels) is too small to display more than a few characters. To display a longer label, we need to widen the button:</p>
<pre lang="matlab">
% Make the button wider than the standard 23 pixels
newSize = java.awt.Dimension(50, jButton.getHeight);
jButton.setMaximumSize(newSize)
jButton.setPreferredSize(newSize)
jButton.setSize(newSize)
</pre>
<p>Using a text label does not prevent us from also displaying an icon: In addition to the text label, we can also display a standard icon (by setting the button&#8217;s <b>CData</b> property in standard Matlab). This icon will be displayed to the left of the text label. You can widen the button, as shown in the code snippet above, to make space for both the icon and the label. If you want to move the label to a different location relative to the icon, simply modify the Java component&#8217;s HorizontalTextPosition property:</p>
<pre lang="matlab">
jButton.setHorizontalTextPosition(jButton.RIGHT);   % label right of icon (=default)
jButton.setHorizontalTextPosition(jButton.CENTER);  % label on top of icon
jButton.setHorizontalTextPosition(jButton.LEFT);    % label left of icon
</pre>
<p>In summary, here&#8217;s the code snippet that generated the screenshot above:</p>
<pre lang="matlab">
% Get the Matlab & Java handles to the figure's toolbar
hToolbar = findall(hFig, 'tag','FigureToolBar');     % get the figure's toolbar handle
jToolbar = hToolbar.JavaContainer.getComponentPeer;  % get the toolbar's Java handle
% Button #1: label only, no icon, 23x23 pixels
h1 = uipushtool(hToolbar);
drawnow; pause(0.01);
jButton = jToolbar.getComponent(jToolbar.getComponentCount-1);
jButton.setText('1')
% Create the icon CData from an icon file
graphIcon = fullfile(matlabroot,'/toolbox/matlab/icons/plotpicker-plot.gif');
[graphImg,map] = imread(graphIcon);
map(map(:,1)+map(:,2)+map(:,3)==3) = NaN;  % Convert white pixels => transparent background
cdata = ind2rgb(graphImg,map);
% Button #2: label centered on top of icon, 23x23 pixels
h2 = uipushtool(hToolbar, 'CData',cdata);
drawnow; pause(0.01);
jButton = jToolbar.getComponent(jToolbar.getComponentCount-1);
jButton.setText('2')
jButton.setHorizontalTextPosition(jButton.CENTER)
% Button #3: label on right of icon, 50x23 pixels
h3 = uipushtool(hToolbar, 'CData',cdata);
drawnow; pause(0.01);
jButton = jToolbar.getComponent(jToolbar.getComponentCount-1);
jButton.setText('3...')
d = java.awt.Dimension(50, jButton.getHeight);
jButton.setMaximumSize(d); jButton.setPreferredSize(d); jButton.setSize(d)
% Button #4: label on left of icon, 70x23 pixels
h4 = uipushtool(hToolbar, 'CData',cdata);
drawnow; pause(0.01);
jButton = jToolbar.getComponent(jToolbar.getComponentCount-1);
jButton.setText('and 4:')
jButton.setHorizontalTextPosition(jButton.LEFT)
d = java.awt.Dimension(70, jButton.getHeight);
jButton.setMaximumSize(d); jButton.setPreferredSize(d); jButton.setSize(d)
</pre>
<p>Many additional toolbar customizations can be found <a href="/articles/tag/toolbar" target="_blank">here</a> and in my book &#8220;<a href="/books/matlab-java" target="_blank"><b>Undocumented Secrets of MATLAB-Java Programming</b></a>&#8220;. If you&#8217;d like me to design a professional-looking GUI for you, please <a href="/consulting" target="_blank">contact me</a>.<br />
Caveat emptor: all this only works with the regular Java-based GUI figures, not web-based (&#8220;App-Designer&#8221;) uifigures.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/toolbar-button-labels">Toolbar button labels</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-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>
<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/adding-a-search-box-to-figure-toolbar" rel="bookmark" title="Adding a search box to figure toolbar">Adding a search box to figure toolbar </a> <small>An interactive search-box can easily be added to a Matlab figure toolbar for enhanced user experience. ...</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>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/toolbar-button-labels/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Using SQLite in Matlab</title>
		<link>https://undocumentedmatlab.com/articles/using-sqlite-in-matlab?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-sqlite-in-matlab</link>
					<comments>https://undocumentedmatlab.com/articles/using-sqlite-in-matlab#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 27 Dec 2017 21:53:54 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[JDBC]]></category>
		<category><![CDATA[Performance]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7255</guid>

					<description><![CDATA[<p>SQLite databases can be accessed in a variety of different ways in Matlab. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/using-sqlite-in-matlab">Using SQLite in 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/secure-ssl-connection-between-matlab-and-postgresql" rel="bookmark" title="Secure SSL connection between Matlab and PostgreSQL">Secure SSL connection between Matlab and PostgreSQL </a> <small>It is tricky, but quite possible, to use SSL to connect Matlab to a PostgreSQL database. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-matlab-jdbc-sql-queries" rel="bookmark" title="Speeding up Matlab-JDBC SQL queries">Speeding up Matlab-JDBC SQL queries </a> <small>Fetching SQL ResultSet data from JDBC into Matlab can be made significantly faster. ...</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/sending-html-emails-from-matlab" rel="bookmark" title="Sending HTML emails from Matlab">Sending HTML emails from Matlab </a> <small>Matlab's sendmail only sends simple text messages by default; a simple hack can cause it to send HTML-formatted messages. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>MathWorks invests a huge amount of effort in recent years on supporting large distributed databases. The business case for this focus is entirely understandable, but many Matlab users have much simpler needs, which are often served by the light-weight open-source <a href="http://sqlite.org" rel="nofollow" target="_blank">SQLite database</a> (which claims to be the most widely-used database worldwide). Although SQLite is very widely used, and despite the fact that built-in support for SQLite is included in Matlab (for its internal use), MathWorks has chosen not to expose any functionality or wrapper function that would enable end-users to access it. In any case, I recently came across a need to do just that, when a consulting client asked me to create an interactive data-browser for their SQLite database that would integrate with their Matlab program:<br />
<center><img decoding="async" src="https://undocumentedmatlab.com/images/DataBrowser_2.png" alt="SQLite data browser" title="SQLite data browser" width="80%" style="max-width:716px;" /></center><br />
In today&#8217;s post I will discuss several possible mechanisms to integrate SQLite in Matlab code, and you can take your pick among them. Except for the Database Toolbox, all the alternatives are free (open-source) libraries (even the commercial Database Toolbox relies on one of the open-source libraries, by the way).<br />
<span id="more-7255"></span></p>
<h3 id="sqlite4java">sqlite4java</h3>
<p><code>sqlite4java</code> is a Java package by <a href="http://almworks.com" rel="nofollow" target="_blank">ALM Works</a> that is bundled with Matlab for the past several years (in the <i>%matlabroot%/java/jarext/sqlite4java/</i> folder). This is a lightweight open-source package that provides a minimalist and fast (although not very convenient) interface to SQLite. You can either use the package that comes with your Matlab installation, or download and use the latest version from <a href="https://bitbucket.org/almworks/sqlite4java" rel="nofollow" target="_blank">the project repository</a>, where you can also find documentation.<br />
Mark Mikofski <a href="http://poquitopicante.blogspot.co.il/2015/03/sqlite-in-matlab.html" rel="nofollow" target="_blank">exposed</a> this hidden nugget back in 2015, and you are welcome to view his post for additional details. Here&#8217;s a sample usage:</p>
<pre lang="matlab">
% Open the DB data file
db = com.almworks.sqlite4java.SQLiteConnection(java.io.File('C:\Yair\Data\IGdb 2017-11-13.sqlite'));
db.open;
% Prepare an SQL query statement
stmt = db.prepare(['select * from data_table where ' conditionStr]);
% Step through the result set rows
row = 1;
while stmt.step
   numericValues(row) = stmt.columnInt(0);    % column #0
   stringValues{row}  = stmt.columnString(1); % column #1
end
% Cleanup
stmt.dispose
db.dispose
</pre>
<p>Note that since <code>sqlite4java</code> uses a proprietary interface (similar, but not identical, to JDBC), it can take a bit of time to get used to it. I am generally a big fan of preferring built-in components over externally-installed ones, but in this particular case I prefer other alternatives.</p>
<h3 id="JDBC">JDBC</h3>
<p><a href="http://www.oracle.com/technetwork/java/javase/jdbc/index.html" rel="nofollow" target="_blank">JDBC</a> (Java Database Connectivity) is the industry standard for connectivity to databases. Practically all databases nowadays have at least one JDBC connector, and many DBs have multiple JDBC drivers created by different groups. As long as they all adhere to the JDBC interface standard, these drivers are all equivalent and you can choose between them based on availability, cost, support, license, performance and other similar factors. SQLite is no exception to this rule, and has several JDBC driver implementations, including xerial&#8217;s <a href="https://bitbucket.org/xerial/sqlite-jdbc" rel="nofollow" target="_blank"><code>sqlite-jdbc</code></a> (also <a href="http://poquitopicante.blogspot.co.il/2015/03/sqlite-in-matlab.html" rel="nofollow" target="_blank">discussed by Mark Mikofski</a>) and <a href="https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/sqlitebot/sqlitejdbc-v056.jar" rel="nofollow" target="_blank"><code>sqlitejdbc</code></a>. If you ask me,<br />
 <code>sqlite-jdbc</code> is better as it is being maintained with new versions released periodically.<br />
The example above would look something like this with <code>sqlite-jdbc</code>:</p>
<pre lang="matlab">
% Add the downloaded JAR library file to the dynamic Java classpath
javaaddpath('C:\path\to\sqlite\sqlite-jdbc-3.21.0.jar')
% Open the DB file
jdbc = org.sqlite.JDBC;
props = java.util.Properties;
conn = jdbc.createConnection('jdbc:sqlite:C:\Yair\Data\IGdb 2017-11-13.sqlite',props);  % org.sqlite.SQLiteConnection object
% Prepare and run an SQL query statement
sqlStr = ['select * from data_table where ' conditionStr];
stmt = conn.createStatement;     % org.sqlite.jdbc4.JDBC4Statement object
rs = stmt.executeQuery(sqlStr);  % org.sqlite.jdbc4.JDBC4ResultSet object
% Step through the result set rows
rows = 1;
while rs.next
   numericValues(row) = rs.getLong('ID');
   stringValues{row}  = rs.getString('Name');
end
% Cleanup
rs.close
stmt.close
conn.close
</pre>
<h3 id="toolbox">Database toolbox</h3>
<p>In addition to all the above, MathWorks sells the Database Toolbox which has an <a href="https://www.mathworks.com/help/database/ug/working-with-the-matlab-interface-to-sqlite.html" rel="nofollow" target="_blank">integral SQLite connector</a>, in two flavors &#8211; native and JDBC (the JDBC connector is simply <code>sqlite-jdbc</code> that I mentioned above, see a <a href="https://gist.github.com/cbcunc/e2bc3ef170544e4bf0f0" rel="nofollow" target="_blank">short discussion here</a>).<br />
I assume that the availability of this feature in the DB toolbox is the reason why MathWorks has never created a documented wrapper function for the bundled <code>sqlite4java</code>. I could certainly understand this from a business perspective. Still, with so many free alternatives available as discussed in this post, I see not reason to purchase the toolbox merely for its SQLite connector. Then again, if you need to connect to several different database types, not just SQLite, then getting the toolbox might make sense.</p>
<h3 id="mksqlite">mksqlite</h3>
<p>My personal favorite is actually none of these Java-based connectors (surprise, surprise), but rather the open-source <a href="http://mksqlite.sourceforge.net" rel="nofollow" target="_blank"><code>mksqlite</code> connector</a> by <a href="http://www.kortmann.de" rel="nofollow" target="_blank">Martin Kortmann</a> and <a href="https://github.com/AndreasMartin72" rel="nofollow" target="_blank">Andreas Martin</a>. This is a native (Mex-file) connector that acts as a direct Matlab function. The syntax is pretty straight-forward and supports SQL queries. IMHO, its usage is a much simpler than with any of the other alternatives:</p>
<pre lang="matlab">
% Open the DB file
mksqlite('open', 'C:\Yair\Data\IGdb 2017-11-13.sqlite');
% Query the database
results = mksqlite(['select * from data_table where ' conditionStr]);
numericValues = [results.ID];
stringValues  = {results.Name};
% Cleanup
mksqlite('close');
</pre>
<p>Can it be any simpler than this!?<br />
However, the main benefit of <code>mksqlite</code> over the other connectors is not its simplicity but the connector&#8217;s speed. This speed is due to the fact that the query is vectorized and we do not need to loop over all the separate data rows and fields. With the other connectors, it is actually not the loop that takes so long in Matlab, but rather the overheads and inefficiencies of numerous library calls to fetch one single value at a time from the result-set &#8211; this is avoided in <code>mksqlite</code> where there is only a single call. This results in lightning speed: A couple of years ago I consulted to a client who used a JDBC connector to an SQLite database; by switching from a JDBC connector to <code>mksqlite</code>, I reduced the execution time from 7 secs to 70 msecs &#8211; a 100x speedup! In that specific case, this made the difference between an unusable program and a highly interactive/responsive one.</p>
<h3 id="alternatives">Other alternatives</h3>
<p>In addition to all the above, we can also use a <a href="http://www.codingtricks.biz/working-with-sqlite-database-in-matlab/" rel="nofollow" target="_blank">.NET-based connector</a> or a <a href="https://www.pythoncentral.io/introduction-to-sqlite-in-python/" rel="nofollow" target="_blank">Python one</a> &#8211; I leave these as an exercise for the reader&#8230;<br />
Have I forgotten some important alternative? Or perhaps you have have some related tip you&#8217;d like to share? If so, then please leave a comment below.<br />
Happy New Year everybody!</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/using-sqlite-in-matlab">Using SQLite in 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/secure-ssl-connection-between-matlab-and-postgresql" rel="bookmark" title="Secure SSL connection between Matlab and PostgreSQL">Secure SSL connection between Matlab and PostgreSQL </a> <small>It is tricky, but quite possible, to use SSL to connect Matlab to a PostgreSQL database. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-matlab-jdbc-sql-queries" rel="bookmark" title="Speeding up Matlab-JDBC SQL queries">Speeding up Matlab-JDBC SQL queries </a> <small>Fetching SQL ResultSet data from JDBC into Matlab can be made significantly faster. ...</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/sending-html-emails-from-matlab" rel="bookmark" title="Sending HTML emails from Matlab">Sending HTML emails from Matlab </a> <small>Matlab's sendmail only sends simple text messages by default; a simple hack can cause it to send HTML-formatted messages. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/using-sqlite-in-matlab/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
	</channel>
</rss>
