HTML – Undocumented Matlab https://undocumentedmatlab.com/blog_old Charting Matlab's unsupported hidden underbelly Tue, 29 Oct 2019 15:26:09 +0000 en-US hourly 1 https://wordpress.org/?v=4.4.1 Matlab GUI training seminars – Zurich, 29-30 August 2017https://undocumentedmatlab.com/blog_old/matlab-gui-training-seminars-zurich-29-30-august-2017 https://undocumentedmatlab.com/blog_old/matlab-gui-training-seminars-zurich-29-30-august-2017#respond Fri, 04 Aug 2017 09:37:52 +0000 https://undocumentedmatlab.com/?p=6992 Related posts:
  1. Customizing Matlab labels Matlab's text uicontrol is not very customizable, and does not support HTML or Tex formatting. This article shows how to display HTML labels in Matlab and some undocumented customizations...
  2. GUI integrated browser control A fully-capable browser component is included in Matlab and can easily be incorporated in regular Matlab GUI applications. This article shows how....
  3. FindJObj GUI – display container hierarchy The FindJObj utility can be used to present a GUI that displays a Matlab container's internal Java components, properties and callbacks....
  4. Inactive Control Tooltips & Event Chaining Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....
]]>
Advanced Matlab training, Zurich 29-30 August 2017
Advanced Matlab training courses/seminars will be presented by me (Yair) in Zürich, Switzerland on 29-30 August, 2017:

  • August 29 (full day) – Interactive Matlab GUI
  • August 30 (full day) – Advanced Matlab GUI

The seminars are targeted at Matlab users who wish to improve their program’s usability and professional appearance. Basic familiarity with the Matlab environment and coding/programming is assumed. The courses will present a mix of both documented and undocumented aspects, which is not available anywhere else. The curriculum is listed below.

This is a unique opportunity to enhance your Matlab coding skills and improve your program’s usability in a couple of days.

If you are interested in either or both of these seminars, please Email me (altmany at gmail dot com).

I can also schedule a dedicated visit to your location, for onsite Matlab training customized to your organization’s specific needs. Additional information can be found on my Training page.

Around the time of the training, I will be traveling to various locations around Switzerland. If you wish to meet me in person to discuss how I could bring value to your project, then please email me (altmany at gmail):

  • Geneva: Aug 22 – 27
  • Bern: Aug 27 – 28
  • Zürich: Aug 28 – 30
  • Stuttgart: Aug 30 – 31
  • Basel: Sep 1 – 3

 Email me


Interactive Matlab GUI – 29 August, 2017

  1. Introduction to Matlab Graphical User Interfaces (GUI)
    • Design principles and best practices
    • Matlab GUI alternatives
    • Typical evolution of Matlab GUI developers
  2. GUIDE – MATLAB’s GUI Design Editor
    • Using GUIDE to design a custom GUI
    • Available built-in MATLAB uicontrols
    • Customizing uicontrols
    • Important figure and uicontrol properties
    • GUIDE utility windows
    • The GUIDE-generated file-duo
  3. Customizing GUI appearance and behavior
    • Programmatic GUI creation and control
    • GUIDE vs. m-programming
    • Attaching callback functionality to GUI components
    • Sharing data between GUI components
    • The handles data struct
    • Using handle visibility
    • Position, size and units
    • Formatting GUI using HTML
  4. Uitable
    • Displaying data in a MATLAB GUI uitable
    • Controlling column data type
    • Customizing uitable appearance
    • Reading uitable data
    • Uitable callbacks
    • Additional customizations using Java
  5. Matlab’s new App Designer and web-based GUI
    • App Designer environment, widgets and code
    • The web-based future of Matlab GUI and assumed roadmap
    • App Designer vs. GUIDE – pros and cons comparison
  6. Performance and interactivity considerations
    • Speeding up the initial GUI generation
    • Improving GUI responsiveness
    • Actual vs. perceived performance
    • Continuous interface feedback
    • Avoiding common performance pitfalls
    • Tradeoff considerations

At the end of this seminar, you will have learned how to:

  • apply GUI design principles in Matlab
  • create simple Matlab GUIs
  • manipulate and customize graphs, images and GUI components
  • display Matlab data in a variety of GUI manners, including data tables
  • decide between using GUIDE, App Designer and/or programmatic GUI
  • understand tradeoffs in design and run-time performance
  • comprehend performance implications, to improve GUI speed and responsiveness

Advanced Matlab GUI – 30 August, 2017

  1. Advanced topics in Matlab GUI
    • GUI callback interrupts and re-entrancy
    • GUI units and resizing
    • Advanced HTML formatting
    • Using hidden (undocumented) properties
    • Listening to action and property-change events
    • Uitab, uitree, uiundo and other uitools
  2. Customizing the figure window
    • Creating and customizing the figure’s main menu
    • Creating and using context menus
    • Creating and customizing figure toolbars
  3. Using Java with Matlab GUI
    • Matlab and Java Swing
    • Integrating Java controls in Matlab GUI
    • Handling Java events as Matlab callbacks
    • Integrating built-in Matlab controls/widgets
    • Integrating JIDE’s advanced features and professional controls
    • Integrating 3rd-party Java components: charts/graphs/widgets/reports
  4. Advanced Matlab-Java GUI
    • Customizing standard Matlab uicontrols
    • Figure-level customization (maximize/minimize, disable etc.)
    • Containers and position – Matlab vs. Java
    • Compatibility aspects and trade-offs
    • Safe programming with Java in Matlab
    • Java’s EDT and timing considerations
    • Deployment (compiler) aspects

At the end of this seminar, you will have learned how to:

  • customize the figure toolbar and main menu
  • use HTML to format GUI appearance
  • integrate Java controls in Matlab GUI
  • customize your Matlab GUI to a degree that you never knew was possible
  • create a modern-looking professional GUI in Matlab
]]>
https://undocumentedmatlab.com/blog_old/matlab-gui-training-seminars-zurich-29-30-august-2017/feed 0
Sending HTML emails from Matlabhttps://undocumentedmatlab.com/blog_old/sending-html-emails-from-matlab https://undocumentedmatlab.com/blog_old/sending-html-emails-from-matlab#comments Wed, 02 Aug 2017 21:19:42 +0000 https://undocumentedmatlab.com/?p=6986 Related posts:
  1. Uitable sorting Matlab's uitables can be sortable using simple undocumented features...
  2. Uitable customization report Matlab's uitable can be customized in many different ways. A detailed report explains how. ...
  3. Types of undocumented Matlab aspects This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...
  4. Multi-line uitable column headers Matlab uitables can present long column headers in multiple lines, for improved readability. ...
]]>
A few months ago I wrote about various tricks for sending email/text messages from Matlab. Unfortunately, Matlab only sends text emails by default and provides no documented way to send HTML-formatted emails. Text-only emails are naturally very bland and all mail clients in the past 2 decades support HTML-formatted emails. Today I will show how we can send such HTML emails from Matlab.

A quick recap: Matlab’s sendmail function uses Java (specifically, the standard javax.mail package) to prepare and send emails. The Java classes are extremely powerful and so there is no wonder that Mathworks chose to use them rather than reinventing the wheel. However, Matlab’s sendmail function only uses part of the functionality exposed by these classes (admittedly, the most important parts that deal with the basic mail-sending mechanism), and does not expose external hooks or input args that would enable the user to take full advantage of the more advanced features, HTML formatting included.

Only two small changes are needed in sendmail.m to support HTML formatting:

  1. HTML formatting required calling the message-object’s setContent() method, rather than setText().
  2. We need to specify 'text/html' as part of the message’s encoding

To implement these features, change the following (lines #119-130 in the original sendmail.m file of R2017a, changed lines highlighted):

% Construct the body of the message and attachments.
body = formatText(theMessage);
if numel(attachments) == 0    if ~isempty(charset)        msg.setText(body, charset);
    else
        msg.setText(body);
    end
else
    % Add body text.
    messageBodyPart = MimeBodyPart;
    if ~isempty(charset)        messageBodyPart.setText(body, charset);
    ...

to this (changed lines highlighted):

% Construct the body of the message and attachments.
body = formatText(theMessage);
isHtml = ~isempty(body) && body(1) == '<';  % msg starting with '<' indicates HTMLif isHtml    if isempty(charset)        charset = 'text/html; charset=utf-8';    else        charset = ['text/html; charset=' charset];    endendif numel(attachments) == 0  && ~isHtml    if isHtml        msg.setContent(body, charset);    elseif ~isempty(charset)        msg.setText(body, charset);
    else
        msg.setText(body);
    end
    else
        % Add body text.
        messageBodyPart = MimeBodyPart;
        if isHtml            messageBodyPart.setContent(body, charset);        elseif ~isempty(charset)            messageBodyPart.setText(body, charset);
        ...

In addition, I also found it useful to remove the hard-coded 75-character line-wrapping in text messages. This can be done by changing the following (line #291 in the original sendmail.m file of R2017a):

maxLineLength = 75;

to this:

maxLineLength = inf;  % or some other large numeric value

Deployment

It’s useful to note two alternatives for making these fixes:

  • Making the changes directly in %matlabroot%/toolbox/matlab/iofun/sendmail.m. You will need administrator rights to edit this file. You will also need to redo the fix whenever you install Matlab, either installation on a different machine, or installing a new Matlab release. In general, I discourage changing Matlab’s internal files because it is simply not very maintainable.
  • Copying %matlabroot%/toolbox/matlab/iofun/sendmail.m into a dedicated wrapper function (e.g., sendEmail.m) that has a similar function signature and exists on the Matlab path. This has the benefit of working on multiple Matlab releases, and being copied along with the rest of our m-files when we install our Matlab program on a different computer. The downside is that our wrapper function will be stuck with the version of sendmail.m that we copied into it, and we’d lose any possible improvements that Mathworks may implement in future Matlab releases.

The basic idea for the second alternative, the sendEmail.m wrapper, is something like this (the top highlighted lines are the additions made to the original sendmail.m, with everything placed in sendEmail.m on the Matlab path):

function sendEmail(to,subject,theMessage,attachments)%SENDEMAIL Send e-mail wrapper (with HTML formatting)   sendmail(to,subject,theMessage,attachments); 
% The rest of this file is copied from %matlabroot%/toolbox/matlab/iofun/sendmail.m (with the modifications mentioned above):
function sendmail(to,subject,theMessage,attachments)
%SENDMAIL Send e-mail.
%   SENDMAIL(TO,SUBJECT,MESSAGE,ATTACHMENTS) sends an e-mail.  TO is either a
%   character vector specifying a single address, or a cell array of character vector
...

We would then call the wrapper function as follows:

sendEmail('abc@gmail.com', 'email subject', 'regular text message');     % will send a regular text message
sendEmail('abc@gmail.com', 'email subject', '<b><font color="blue">HTML-formatted</font> <i>message');  % HTML-formatted message

In this case, the code automatically infers HTML formatting based on whether the first character in the message body is a ‘<‘ character. Instead, we could just as easily have passed an additional input argument (isHtml) to our sendEmail wrapper function.

Hopefully, in some future Matlab release Mathworks will be kind enough to enable sending 21st-century HTML-formatted emails without needing such hacks. Until then, note that sendmail.m relies on standard non-GUI Java networking classes, which are expected to be supported far into the future, well after Java-based GUI may cease to be supported in Matlab. For this reason I believe that while it seems a bit tricky, the changes that I outlined in today’s post actually have a low risk of breaking in a future Matlab release.

Do you have some other advanced email feature that you use in your Matlab program by some crafty customization to sendmail? If so, please share it in a comment below.

]]>
https://undocumentedmatlab.com/blog_old/sending-html-emails-from-matlab/feed 2
GUI formatting using HTMLhttps://undocumentedmatlab.com/blog_old/gui-formatting-using-html https://undocumentedmatlab.com/blog_old/gui-formatting-using-html#comments Wed, 05 Apr 2017 20:26:44 +0000 https://undocumentedmatlab.com/?p=6877 Related posts:
  1. Icon images & text in Matlab uicontrols HTML can be used to add image icons to Matlab listbox and popup (drop-down) controls. ...
  2. Spicing up Matlab uicontrol tooltips Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...
  3. Multi-line uitable column headers Matlab uitables can present long column headers in multiple lines, for improved readability. ...
  4. Rich-contents log panel Matlab listboxes and editboxes can be used to display rich-contents HTML-formatted strings, which is ideal for log panels. ...
]]>
As I’ve mentioned several times in the past, HTML can be used for simple formatting of GUI controls, including font colors/sizes/faces/angles. With a bit of thought, HTML (and some CSS) can also be used for non-trivial formatting, that would otherwise require the use of Java, such as text alignment, background color, and using a combination of text and icons in the GUI control’s contents.

Alignment

For example, a question that I am often asked (latest example) is whether it is possible to left/center/right align the label within a Matlab button, listbox or table. While Matlab does not (yet) have properties that control alignment in uicontrols, we can indeed use HTML for this. There’s a catch though: if we simply tried to use <div align="left">…, it will not work. No error will be generated but we will not see any visible left-alignment. The reason is that internally, the text is contained within a snugly-fitting box. Aligning anything within a tight-fitting box obviously has no effect.

To solve the problem, we need to tell Matlab (or rather, the HTML interpreter used by the underlying Java control) to widen this internal box. One way to do this is to specify the width of the div tag, which can be enormous in order to span the entire available apace (<div width="999px" align="left">…). Another method is to simulate a simple HTML table that contains a single cell that holds the text, and then tell HTML the table cell’s width:

hButton.String   = '<html><tr><td width=9999 align=left>Left-aligned';  % left-align within a button
hTable.Data{2,1} = '<html><tr><td width=9999 align=right>And right';   % right-align within a specific uitable cell

centered (default) button label   right-aligned button label

Centered (default) and right-aligned button labels

Non-default alignment of uitable cells

Non-default alignment of uitable cells

I discussed the specific aspect of uicontrol content alignment in another post last year.

Background color

The same problem (and solution) applies to background colors: if we don’t enlarge the snugly-fitting internal bounding-box, any HTML bgcolor that we specify would only be shown under the text (i.e., within the internal box’s confines). In order to display bgcolor across the entire control/cell width, we need to enlarge the internal box’s width (the align and bgcolor tags can of course be used together):

hButton.String   = '<html><tr><td width=9999 bgcolor=#ffff00>Yellow';  % bgcolor within a button
hTable.Data{2,1} = '<html><tr><td width=9999 bgcolor=#ffff00>Yellow';  % bgcolor within a specific uitable cell

CSS

We can also use simple CSS, which provides more formatting customizability than plain HTML:

hTable.Data{2,1} = '<html><tr><td width=9999 style="background-color:yellow">Yellow';

HTML/CSS formatting is a poor-man’s hack. It is very crude compared to the numerous customization options available via Java. However, it does provide a reasonable solution for many use-cases, without requiring any Java. I discussed the two approaches for uitable cell formatting in this post.

[Non-]support in uifigures

Important note: HTML formatting is NOT [yet] supported by the new web-based uifigures. While uifigures can indeed be hacked with HTML/CSS content (details), this is not an easy task. Since it should be trivially easy for MathWorks to enable HTML content in the new web-based uifigures, I implore anyone who uses HTML in their Matlab GUI to let MathWorks know about it so that they could prioritize this R&D effort into an upcoming Matlab release. You can send an email to Eric.Sargent at mathworks.com, who handles such aspects in MathWorks’ R&D efforts to transition from Java-based GUIs to web-based ones. In my previous post I spotlit MathWorks user-feedback surveys about users’ use of Java GUI aspects, aimed in order to migrate as many of the use-cases as possible onto the new web-based framework. HTML/CSS support is a natural by-product of the fact that Matlab’s non-web-based GUI is based on Java Swing components (that inherently support HTML/CSS). But unfortunately the MathWorks surveys are specific to the javacomponent function and the figure’s JavaFrame property. In other words, many users might be using undocumented Java aspects by simply using HTML content in their GUI, without ever realizing it or using javacomponent. So I think that in this case a simple email to Eric.Sargent at mathworks.com to let him know how you’re using HTML would be more useful. Maybe one day MathWorks will be kind enough to post a similar survey specific to HTML support, or maybe one day they’s just add the missing HTML support, if only to be done with my endless nagging. :-)

p.s. – I am well aware that we can align and bgcolor buttons in AppDesigner. But we can’t do this with individual table/listbox cells, and in general we can’t use HTML within uifigures without extensive hacks. I merely used the simple examples of button and uitable cell formatting in today’s post to illustrate the issue. So please don’t get hung up on the specifics, but rather on the broader issue of HTML support in uifigures.

And in the meantime, for as long as non-web-based GUI is still supported in Matlab, keep on enjoying the benefits that HTML/CSS provides.

Automated bug-fix emails

In an unrelated matter, I wish to express my Kudos to the nameless MathWorkers behind the scenes who, bit by bit, improve Matlab and the user experience: Over the years I’ve posted a few times my frustrations with the opaqueness of MathWorks’ bug-reporting mechanism. One of my complaints was that users who file bugs are not notified when a fix or workaround becomes available. That at least seems to have been fixed now. I just received a seemingly-automated email notifying me that one of the bugs that I reported a few years ago has been fixed. This is certainly a good step in the right direction, so thank you!

Happy Passover/Easter to all!

]]>
https://undocumentedmatlab.com/blog_old/gui-formatting-using-html/feed 6
Icon images & text in Matlab uicontrolshttps://undocumentedmatlab.com/blog_old/icon-images-in-matlab-uicontrols https://undocumentedmatlab.com/blog_old/icon-images-in-matlab-uicontrols#comments Wed, 28 Sep 2016 10:28:04 +0000 https://undocumentedmatlab.com/?p=6687 Related posts:
  1. Rich-contents log panel Matlab listboxes and editboxes can be used to display rich-contents HTML-formatted strings, which is ideal for log panels. ...
  2. Spicing up Matlab uicontrol tooltips Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...
  3. Aligning uicontrol contents Matlab uicontrols can often be customized using plain HTML/CSS, without need for advanced Java. ...
  4. GUI integrated browser control A fully-capable browser component is included in Matlab and can easily be incorporated in regular Matlab GUI applications. This article shows how....
]]>
One of my consulting clients recently asked me if I knew any builtin Matlab GUI control that could display a list of colormap names alongside their respective image icons, in a listbox or popup menu (drop-down/combo-box):

Matlab listbox with icon images   Matlab popup menu (dropdown/combobox) with icon images

Matlab listbox (left) & popup menu (right) with icon images

My initial thought was that this should surely be possible, since Colormap is a documented figure property, that should therefore be listed inside the inspector window, and should therefore have an associated builtin Java control for the dropdown (just like other inspector controls, which are part of the com.mathworks.mlwidgets package, or possibly as a standalone control in the com.mathworks.mwswing package). To my surprise it turns out that for some unknown reason MathWorks neglected to add the Colormap property (and associated Java controls) to the inspector. This property is fully documented and all, just like Color and other standard figure properties, but unlike them Colormap can only be modified programmatically, not via the inspector window. Matlab does provide the related colormapeditor function and associated dialog window, but I would have expected a simple drop-down of the standard builtin colormaps to be available in the inspector. Anyway, this turned out to be a dead-end.

It turns out that we can relatively easily implement the requested listbox/combo-box using a bit of HTML magic, as I explained last week. The basic idea is for each of the listbox/combobox items to be an HTML string that contains both an <img> tag for the icon and the item label text. For example, such a string might contain something like this (parula is Matlab’s default colormap in HG2, starting in R2014b):

<html><img src="http://www.mathworks.com/help/matlab/ref/colormap_parula.png">parula

parula colormap image

parula colormap image

Of course, it would be a bit inefficient for each of the icons to be fetched from the internet. Luckily, the full set of Matlab documentation is typically installed on the local computer as part of the standard Matlab installation, beneath the docroot folder (e.g., C:\Program Files\Matlab\R2016b\help). In our specific case, the parula colormap image is located in:

imageFilename = [docroot, '/matlab/ref/colormap_parula.png']

Note that for a local image to be accepted by HTML, it needs to follow certain conventions. In our case, the HTML string for displaying the above image is:

<html><img src="file:///C:/Program%20Files/Matlab/R2016b/help/matlab/ref/colormap_parula.png">parula

Warning: it’s easy when dealing with HTML images in Matlab to get the format confused, resulting in a red-x icon. I discussed this issue some 4 years ago, which is still relevant.

How can we get the list of available builtin colormaps? The standard Matlab way of doing this would be something like this:

>> possibleColormaps = set(gcf,'Colormap')
possibleColormaps = 
     {}

but as we can see, for some unknown reason (probably another MathWorks omission), Matlab does not list the names of its available builtin colormaps.

Fortunately, all the builtin colormaps have image filenames that follow the same convention, which make it easy to get this list by simply listing the names of the relevant files, from which we can easily create the necessary HTML strings:

>> iconFiles = dir([docroot, '/matlab/ref/colormap_*.png']);
 
>> colormapNames = regexprep({iconFiles.name}, '.*_(.*).png', '$1')
colormapNames =  
  Columns 1 through 9
    'autumn'    'bone'    'colorcube'    'cool'    'copper'    'flag'    'gray'    'hot'    'hsv'
  Columns 10 through 18
    'jet'    'lines'    'parula'    'pink'    'prism'    'spring'    'summer'    'white'    'winter'
 
>> htmlStrings = strcat('<html><img width=200 height=10 src="file:///C:/Program%20Files/Matlab/R2016a/help/matlab/ref/colormap_', colormapNames', '.png">', colormapNames')
str = 
    '<html><img width=200 height=10 src="file:///C:/Program%20Files/Matlab/R2016a/help/matlab/ref/colormap_autumn.png">autumn'
    '<html><img width=200 height=10 src="file:///C:/Program%20Files/Matlab/R2016a/help/matlab/ref/colormap_bone.png">bone'
    '<html><img width=200 height=10 src="file:///C:/Program%20Files/Matlab/R2016a/help/matlab/ref/colormap_colorcube.png">colorcube'
    ...
 
>> hListbox = uicontrol(gcf, 'Style','listbox', 'Units','pixel', 'Pos',[10,10,270,200], 'String',htmlStrings);
>> hPopup   = uicontrol(gcf, 'Style','popup',   'Units','pixel', 'Pos',[10,500,270,20], 'String',htmlStrings);

…which results in the screenshots at the top of this post.

Note how I scaled the images to 10px high (so that the labels would be shown and not cropped vertically) and 200px wide (so that it becomes narrower than the default 434px). There’s really no need in this case for the full 434×27 image size – such flat images scale very nicely, even when their aspect ratio is not preserved. You can adjust the height and width values for a best fit with you GUI.

Unfortunately, it seems that HTML strings are not supported in the new web-based uifigure controls. This is not really Matlab’s fault because the way to customize labels in HTML controls is via CSS: directly embedding HTML code in labels does not work (it’s a Java-Swing feature, not a browser feature). I really hope that either HTML or CSS processing will be enabled for web-based uicontrol in a future Matlab release, because until that time uifigure uicontrols will remain seriously deficient compared to standard figure uicontrols. Until then, if we must use uifigures and wish to customize our labels or listbox items, we can directly access the underlying web controls, as Iliya explained here.


A blog reader recently complained that I’m abusing Swing and basically making Matlab work in unnatural ways, “something it was never meant to be“. I feel that using HTML as I’ve shown last week and in this post would fall under the same category in his eyes. To him and to others who complain I say that I have absolutely no remorse about doing this. When I purchase anything I have the full rights (within the scope of the license) to adapt it in whatever way fits my needs. As a software developer and manager for over 25 years, I’ve developed in dozens of programming languages and environments, and I still enjoy [ab]using Matlab. Matlab is a great environment to get things done quickly and if this sometimes requires a bit of HTML or Java hacks that make some people cringe, then that’s their problem, not mine – I’m content with being able to do in Matlab [nearly] everything I want, quickly, and move on to the next project. As long as it gets the job done, that’s fine by me. If this makes me more of an engineer than a computer scientist, then so be it.

On the flip side, I say to those who claim that Matlab is lacking in this or that aspect, that in most likelihood the limitation is only in their minds, not in Matlab – we can do amazing stuff with Matlab if we just open our minds, and possibly use some undocumented hacks. I’m not saying that Matlab has no limitations, I’m just saying that in most cases they can be overcome if we took the time and trouble to look for a solution. Matlab is a great tool and yet many people are not aware of its potential. Blaming Matlab for its failings is just an easy excuse in many cases. Of course, MathWorks could help my crusade on this subject by enabling useful features such as easy GUI component customizations…

On this sad day, I wish you all Shanah Tova!

]]>
https://undocumentedmatlab.com/blog_old/icon-images-in-matlab-uicontrols/feed 6
Aligning uicontrol contentshttps://undocumentedmatlab.com/blog_old/aligning-uicontrol-contents https://undocumentedmatlab.com/blog_old/aligning-uicontrol-contents#comments Thu, 22 Sep 2016 13:10:18 +0000 https://undocumentedmatlab.com/?p=6663 Related posts:
  1. Spicing up Matlab uicontrol tooltips Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...
  2. Rich-contents log panel Matlab listboxes and editboxes can be used to display rich-contents HTML-formatted strings, which is ideal for log panels. ...
  3. Multi-line uitable column headers Matlab uitables can present long column headers in multiple lines, for improved readability. ...
  4. Undocumented button highlighting Matlab button uicontrols can easily be highlighted by simply setting their Value property. ...
]]>
Matlab automatically aligns the text contents of uicontrols: button labels are centered, listbox contents are left-aligned, and table cells align depending on their contents (left-aligned for strings, centered for logical values, and right-aligned for numbers). Unfortunately, the control’s HorizontalAlignment property is generally ignored by uicontrols. So how can we force Matlab buttons (for example) to have right-aligned labels, or for listbox/table cells to be centered? Undocumented Matlab has the answer, yet again…

It turns out that there are at least two distinct ways to set uicontrol alignment, using HTML and using Java. Today I will only discuss the HTML variant.

The HTML method relies on the fact that Matlab uicontrols accept and process HTML strings. This was true ever since Matlab GUI started relying on Java Swing components (which inherently accept HTML labels) over a decade ago. This is expected to remain true even in Matlab’s upcoming web-based GUI system, since Matlab would need to consciously disable HTML in its web components, and I see no reason for MathWorks to do so. In short, HTML parsing of GUI control strings is here to stay for the foreseeable future.

% note: no need to close HTML tags, e.g. </font></html>
uicontrol('Style','list', 'Position',[10,10,70,70], 'String', ...
          {'<HTML><FONT color="red">Hello</Font></html>', 'world', ...
           '<html><font style="font-family:impact;color:green"><i>What a', ...
           '<Html><FONT color="blue" face="Comic Sans MS">nice day!'});

Listbox with HTML items

Listbox with HTML items

While HTML formatting is generally frowned-upon compared to the alternatives, it provides a very quick and easy way to format text labels in various different manners, including using a combination of font faces, sizes, colors and other aspects (bold, italic, super/sub-script, underline etc.) within a single text label. This is naturally impossible to do with Matlab’s standard properties, but is super-easy with HTML placed in the label’s String property.

Unfortunately, while Java Swing (and therefore Matlab) honors only a [large] sub-set of HTML and CSS. The most important directives are parsed but some others are not, and this is often difficult to debug. Luckily, using HTML and CSS there are often multiple ways to achieve the same visual effect, so if one method fails we can usually find an alternative. Such was the case when a reader asked me why the following seemingly-simple HTML snippet failed to right-align his button label:

hButton.String = '<html><div style="text-align:right">text';

As I explained in my answer, it’s not Matlab that ignores the CSS align directive but rather the underlying Swing behavior, which snugly fits the text in the center of the button, and of course aligning text within a tight-fitting box has no effect. The workaround that I suggested simply forces Swing to use a non-tightly-fitting boundary box, within which we can indeed align the text:

pxPos = getpixelposition(hButton);
hButton.String = ['<html><div width="' num2str(pxPos(3)-20) 'px" align="right">text'];  % button margins use 20px

centered (default) button label   right-aligned button label

Centered (default) and right-aligned button labels

This solution is very easy to set up and maintain, and requires no special knowledge other than a bit of HTML/CSS, which most programmers know in this day and age.

Of course, the solution relies on the actual button size. So, if the button is created with normalized units and changes its size when its parent container is resized, we’d need to set a callback function on the parent (e.g., SizeChangedFcn of a uipanel) to automatically adjust the button’s string based on its updated size. A better solution that would be independent of the button’s pixel-size and would work even when the button is resized needs to use Java.

A related solution for table cells uses a different HTML-based trick: this time, we embed an HTML table cell within the Matlab control’s cell, employing the fact that HTML table cells can easily be aligned. We just need to ensure that the HTML cell is defined to be larger than the actual cell width, so that the alignment fits well. We do this by setting the HTML cell width to 9999 pixels (note that the tr and td HTML tags are necessary, but the table tag is optional):

uitable('Units','norm','Pos',[0,0,0.3,0.3], 'Data', ...
        {'Left', ...
         '<html><tr><td align=center width=9999>Center', ...
         '<html><tr><td align=right  width=9999>Right'});

Non-default alignment of uitable cells

Non-default alignment of uitable cells

As noted above, a better solution might be to set the underlying Java component’s alignment properties (or in the case of the uitable, its underlying JTable component’s cellrenderer’s alignment). But in the general case, simple HTML such as above could well be sufficient.

]]>
https://undocumentedmatlab.com/blog_old/aligning-uicontrol-contents/feed 6
Customizing uifigures part 2https://undocumentedmatlab.com/blog_old/customizing-uifigures-part-2 https://undocumentedmatlab.com/blog_old/customizing-uifigures-part-2#comments Wed, 07 Sep 2016 17:00:57 +0000 https://undocumentedmatlab.com/?p=6635 Related posts:
  1. Customizing uifigures part 3 As I have repeatedly posted in recent years, Matlab is advancing towards web-based GUI. The basic underlying technology is more-or-less stable: an HTML/Javascript webpage that is created-on-the-fly and rendered in...
  2. Matlab callbacks for uifigure JavaScript events Matlab callback code can be attached to JavaScript events in web-based uifigures. ...
  3. FindJObj – find a Matlab component’s underlying Java object The FindJObj utility can be used to access and display the internal components of Matlab controls and containers. This article explains its uses and inner mechanism....
  4. Disabling menu entries in deployed docked figures Matlab's standard menu items can and should be removed from deployed docked figures. This article explains how. ...
]]>
I would like to introduce guest blogger Iliya Romm of Israel’s Technion Turbomachinery and Heat Transfer Laboratory. Today Iliya will discuss how Matlab’s new web-based figures can be customized with user-controlled CSS and JavaScript code.

When we compare the documented properties of a “classic” uicontrol with an App Designer control such as uicheckbox, we see lists of 42 and 15 properties, respectively. At first glance, this implies that our ability to customize App Designer elements is relatively very limited. This is surely a disquieting conclusion, especially for those used to being able to change most aspect of their Matlab figures via Java. Fortunately, such a conclusion is quite far from reality, as we will shortly see.

To understand this claim, we need to consider a previous post on this blog, where Yair discussed how uifigures are actually HTML webpages rendered by Matlab. As such, they have a DOM that can be accessed and manipulated through JavaScript commands to achieve various visual customizations. Today we’ll explore the structure of the uifigure webpage; take a look at some possibilities provided by the Dojo Toolkit; and see how to use Dojo to customize uifigure controls visually using CSS styles and/or HTML attributes.

User customizations of Matlab uifigures (click to zoom-in)
User customizations of Matlab uifigures (click to zoom-in)

A brief introduction to CSS

CSS stands for Cascading Style Sheets. As described on the official webpage of W3C (which governs web standards):

CSS is the language for describing the presentation of Web pages, including colors, layout, and fonts. CSS is independent of HTML. This is referred to as the separation of structure (or: content) from presentation.

CSS rules (or “styles”) can be defined in one of three places:

  • A separate file, such as the main.css that Matlab uses for uifigures (this file is found minified in %matlabroot%\toolbox\matlab\uitools\uifigureappjs\release\gbtclient\css)
  • An inline block inside the HTML’s <head> section
  • Directly within a DOM node

Deciding which of the above to use, is largely a choice of the right tool for the job. Usually, the first two choices should be preferred, as they adhere to the “separation of structure and presentation” idea better. However, in the scope of this demonstration, we’ll be using mostly the 3rd option, because it allows us not to worry about possible CSS precedence issues (suggested read).

The syntax of CSS is generally: selector { property: value }, but it can have other forms as well.

Getting down to business

Let us consider a very basic uifigure that only contains a uitextarea and its label:

Simple demo uifigure with a TextArea and label

Simple demo uifigure with a TextArea and label

The auto-generated code for it is:

classdef DOMdemo < matlab.apps.AppBase
 
    % Properties that correspond to app components
    properties (Access = public)
        UIFigure      matlab.ui.Figure           % UI Figure
        LabelTextArea matlab.ui.control.Label    % Text Area
        TextArea      matlab.ui.control.TextArea % This is some text.        
    end
 
    methods (Access = private)
        % Code that executes after component creation
        function startupFcn(app)
        end
    end
 
    % App initialization and construction
    methods (Access = private)
 
        % Create UIFigure and components
        function createComponents(app)
            % Create UIFigure
            app.UIFigure = uifigure;
            app.UIFigure.Position = [100 100 280 102];
            app.UIFigure.Name = 'UI Figure';
            setAutoResize(app, app.UIFigure, true)
 
            % Create LabelTextArea
            app.LabelTextArea = uilabel(app.UIFigure);
            app.LabelTextArea.HorizontalAlignment = 'right';
            app.LabelTextArea.Position = [16 73 62 15];
            app.LabelTextArea.Text = 'Text Area';
 
            % Create TextArea
            app.TextArea = uitextarea(app.UIFigure);
            app.TextArea.Position = [116 14 151 60];
            app.TextArea.Value = {'This is some text.'};
        end
    end
 
    methods (Access = public)
 
        % Construct app
        function app = DOMdemo()
            % Create and configure components
            createComponents(app)
 
            % Register the app with App Designer
            registerApp(app, app.UIFigure)
 
            % Execute the startup function
            runStartupFcn(app, @startupFcn)
 
            if nargout == 0
                clear app
            end
        end
 
        % Code that executes before app deletion
        function delete(app)
            % Delete UIFigure when app is deleted
            delete(app.UIFigure)
        end
    end
end

Let’s say we want to modify certain aspects of the TextArea widget, such as the text color, background, and/or horizontal alignment. The workflow for styling elements involves:

  1. Find the handle to the webfigure
  2. Find the DOM node we want to modify
  3. Find the property name that corresponds to the change we want
  4. Find a way to manipulate the desired node from Matlab

Step 1: Find the handle to the webfigure

The first thing we need to do is to strategically place a bit of code that would allow us to get the URL of the figure so we can inspect it in our browser:

function startupFcn(app)
   % Customizations (aka "MAGIC GOES HERE"):
   warning off Matlab:HandleGraphics:ObsoletedProperty:JavaFrame
   warning off Matlab:structOnObject    
   while true
      try   
         win = struct(struct(struct(app).UIFigure).Controller).Container.CEF;
         disp(win.URL);
         break
      catch
         disp('Not ready yet!');
         pause(0.5); % Give the figure (webpage) some more time to load
      end
   end
end

This code waits until the page is sufficiently loaded, and then retrieve its local address (URL). The result will be something like this, which can be directly opened in any browser (outside Matlab):

http://localhost:31415/toolbox/matlab/uitools/uifigureappjs/componentContainer.html?channel=/uicontainer/861ef484-534e-4a50-993e-6d00bdba73a5&snc=88E96E

Step 2: Find the DOM node that corresponds to the component that we want to modify

Loading this URL in an external browser (e.g., Chrome, Firefox or IE/Edge) enables us to use web-development addins (e.g., FireBug) to inspect the page contents (source-code). Opening the URL inside a browser and inspecting the page contents, we can see its DOM:

Inspecting the DOM in Firefox (click to zoom-in)
Inspecting the DOM in Firefox (click to zoom-in)

Notice the three data-tag entries marked by red frames. Any idea why there are exactly three nonempty tags like that? This is because our App Designer object, app, contains 3 declared children, as defined in:

createComponents(app):
    app.UIFigure = uifigure;
    app.LabelTextArea = uilabel(app.UIFigure);
    app.TextArea = uitextarea(app.UIFigure);

… and each of them is assigned a random hexadecimal id whenever the app is opened.

Finding the relevant node involved some trial-and-error, but after doing it several times I seem to have found a consistent pattern that can be used to our advantage. Apparently, the nodes with data-tag are always above the element we want to style, sometimes as a direct parent and sometimes farther away. So why do we even need to bother with choosing more accurate nodes than these “tagged” ones? Shouldn’t styles applied to the tagged nodes cascade down to the element we care about? Sure, sometimes it works like that, but we want to do better than “sometimes”. To that end, we would like to select as relevant a node as possible.

Anyway, the next step in the program is to find the data-tag that corresponds to the selected component. Luckily, there is a direct (undocumented) way to get it:

% Determine the data-tag of the DOM component that we want to modify:
hComponent = app.TextArea;  % handle to the component that we want to modify
data_tag = char(struct(hComponent).Controller.ProxyView.PeerNode.getId);  % this part is generic: can be used with any web-based GUI component

Let’s take a look at the elements marked with blue and green borders (in that order) in the DOM screenshot. We see that the data-tag property is exactly one level above these elements, in other words, the first child of the tagged node is an element that contains a widgetid property. This property is very important, as it contains the id of the node that we actually want to change. Think pointers. To summarize this part:

data-tag   =>   widgetid   =>   widget “handle”

We shall use this transformation in Step 4 below.

I wanted to start with the blue-outlined element as it demonstrates this structure using distinct elements. The green-outlined element is slightly strange, as it contains a widgetid that points back to itself. Since this obeys the same algorithm, it’s not a problem.

Step 3: Find the CSS property name that corresponds to the change we want

There is no trick here: it’s just a matter of going through a list of CSS properties and choosing one that “sounds about right” (there are often several ways to achieve the same visual result with CSS). After we choose the relevant properties, we need to convert them to camelCase as per documentation of dojo.style():

If the CSS style property is hyphenated, the JavaScript property is camelCased. For example: “font-size” becomes “fontSize”, and so on.

Note that Matlab R2016a comes bundled with Dojo v1.10.4, rev. f4fef70 (January 11 2015). Other Matlab releases will probably come with other Dojo versions. They will never be the latest version of Dojo, but rather a version that is 1-2 years old. We should keep this in mind when searching the Dojo documentation. We can get the current Dojo version as follows:

>> f=uifigure; drawnow; dojoVersion = matlab.internal.webwindowmanager.instance.windowList(1).executeJS('dojo.version'), delete(f)
dojoVersion =
{"major":1,"minor":10,"patch":4,"flag":"","revision":"f4fef70"}

This tells us that Dojo 1.10.4.f4fef70 is the currently-used version. We can use this information to browse the relevant documentation branch, as well as possibly use different Dojo functions/features.

Step 4: Manipulate the desired element from Matlab

In this demo, we’ll use a combination of several commands:

  • {matlab.internal.webwindow.}executeJS() – For sending JS commands to the uifigure.
  • dojo.query() – for finding nodes inside the DOM.
  • dojo.style() (deprecated since v1.8) – for applying styles to the required nodes of the DOM.
    Syntax: dojo.style(node, style, value);
  • dojo.setAttr (deprecated since v1.8) – for setting some non-style attributes.
    Syntax: dojo.setAttr(node, name, value);

Consider the following JS commands:

  • search the DOM for nodes having a data-tag attribute having the specified value, take their first child of type <div>, and return the value of this child’s widgetid attribute:
    ['dojo.getAttr(dojo.query("[data-tag^=''' data_tag '''] > div")[0],"widgetid")']
  • search the DOM for nodes with id of widgetid, then take the first element of the result and set its text alignment:
    ['dojo.style(dojo.query("#' widgetId(2:end-1) '")[0],"textAlign","center")']
  • append the CSS style defined by {SOME CSS STYLE} to the page (this style can later be used by nodes):
    ['document.head.innerHTML += ''<style>{SOME CSS STYLE}</style>''']);

Putting it all together

It should finally be possible to understand the code that appears in the animated screenshot at the top of this post:

%% 1. Get a handle to the webwindow:
win = struct(struct(struct(app).UIFigure).Controller).Container.CEF;
 
%% 2. Find which element of the DOM we want to edit (as before):
data_tag = char(struct(app.TextArea).Controller.ProxyView.PeerNode.getId);
 
%% 3. Manipulate the DOM via a JS command
% ^ always references a class="vc-widget" element.
widgetId = win.executeJS(['dojo.getAttr(dojo.query("[data-tag^=''' data_tag '''] > div")[0],"widgetid")']);
 
% Change font weight:
dojo_style_prefix = ['dojo.style(dojo.query("#' widgetId(2:end-1) '")[0],'];
win.executeJS([dojo_style_prefix '"fontWeight","900")']);
 
% Change font color:
win.executeJS([dojo_style_prefix '"color","yellow")']);
 
% Add an inline css to the HTML <head>:
win.executeJS(['document.head.innerHTML += ''<style>'...
    '@-webkit-keyframes mymove {50% {background-color: blue;}}'...
    '@keyframes mymove {50% {background-color: blue;}}</style>''']);
 
% Add animation to control:      
win.executeJS([dojo_style_prefix '"-webkit-animation","mymove 5s infinite")']);
 
% Change Dojo theme:
win.executeJS('dojo.setAttr(document.body,''class'',''nihilo'')[0]');
 
% Center text:
win.executeJS([dojo_style_prefix '"textAlign","center")']);

A similar method for center-aligning the items in a uilistbox is described here (using a CSS text-align directive).

The only thing we need to ensure before running code that manipulates the DOM, is that the page is fully loaded. The easiest way is to include a pause() of several seconds right after the createComponents(app) function (this will not interfere with the creation of the uifigure, as it happens on a different thread). I have been experimenting with another method involving webwindow‘s PageLoadFinishedCallback callback, but haven’t found anything elegant yet.

A few words of caution

In this demonstration, we invoked Dojo functions via the webwindow’s JS interface. For something like this to be possible, there has to exist some form of “bridge” that translates Matlab commands to JS commands issued to the browser and control the DOM. We also know that this bridge has to be bi-directional, because binding Matlab callbacks to uifigure actions (e.g. ButtonPushFcn for uibuttons) is a documented feature.

The extent to which the bridge might allow malicious code to control the Matlab process needs to be investigated. Until then, the ability of webwindows to execute arbitrary JS code should be considered a known vulnerability. For more information, see XSS and related vulnerabilities.

Final remarks

It should be clear now that there are actually lots of possibilities afforded by the new uifigures for user customizations. One would hope that future Matlab releases will expose easier and more robust hooks for CSS/JS customizations of uifigure contents. But until that time arrives (if ever), we can make do with the mechanism shown above.

Readers are welcome to visit the GitHub project dedicated to manipulating uifigures using the methods discussed in this post. Feel free to comment, suggest improvements and ideas, and of course submit some pull requests :)

p.s. – it turns out that uifigures can also display MathML. But this is a topic for another post…

]]>
https://undocumentedmatlab.com/blog_old/customizing-uifigures-part-2/feed 3
Rich-contents log panelhttps://undocumentedmatlab.com/blog_old/rich-contents-log-panel https://undocumentedmatlab.com/blog_old/rich-contents-log-panel#comments Wed, 18 Sep 2013 14:00:16 +0000 https://undocumentedmatlab.com/?p=4180 Related posts:
  1. Spicing up Matlab uicontrol tooltips Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...
  2. Aligning uicontrol contents Matlab uicontrols can often be customized using plain HTML/CSS, without need for advanced Java. ...
  3. Icon images & text in Matlab uicontrols HTML can be used to add image icons to Matlab listbox and popup (drop-down) controls. ...
  4. Multi-line uitable column headers Matlab uitables can present long column headers in multiple lines, for improved readability. ...
]]>
I often include a log panel in Matlab applications that process data. By sending messages to the log panel, I can avoid msgbox popups and Command Window messages that interfere with the regular workflow. In Matlab, such log panels typically use a simple listbox or editbox control. The problem with this is that all text messages in the log panel look the same. Matlab does not have a documented way to highlight specific messages or words. Well, this has never stopped us before, has it? :-)

The listbox solution

I have often noted in past articles that most Matlab uicontrols support HTML formatting. We can use a listbox control for our log panel, and use HTML formatting for the various log messages, based on their severity or content. For example:

Listbox with HTML'ed items

Listbox with HTML colored items

uicontrol('Style','list', 'Position',[10,10,70,70], 'String', ...
   {'<html><font color="red">Hello</font></html>', 'world', ...
    '<html><font style="font-family:impact;color:green"><i>What a', ...   % note: </i></font></html> are not needed
    '<html><font color="blue" face="Comic Sans MS">nice day!</font>'});   % note: </html> is not needed

Rich listboxes such as this are very easy to set up and use. As I just showed, all it takes is sending an HTML string to a regular listbox. The down-side is that listboxes only display single-line messages, so if our message is too long we need to manually split it into separate listbox lines, which is rather inconvenient. Using HTML <br/> does not work since the allocated line height remains unchanged. We can fix this by playing around with the underlying Java object‘s RowHeight property, but that again is rather inconvenient.

The editbox solution

Instead of a listbox, I often use a multi-line editbox. Unfortunately, HTML is not as-easy to use in multi-line editbox contents, but as I have shown before, it is indeed possible and actually quite powerful. In fact, I am using such an editbox-based log panel’s in my online presentation at the MATLAB Computational Finance Virtual Conference tomorrow (Thursday Sep 19, 2013 at 2pm EST / 8pm CEST, see details below):

Real-time trading system demo in Matlab (click to zoom)

Real-time trading system demo in Matlab (click to zoom)

We can see in the screenshot that some log messages (the red warning message) can span multiple lines. Moreover, the panels can be interactively dragged/resized, making the multi-line log messages “flow” based on available space. So using an editbox is preferable to a listbox. The solution implemented in the demo is quite simple:

First we define the logging utility function (the icon filenames may need to be changed based on your Matlab release):

function logMessage(jEditbox,text,severity)
   % Ensure we have an HTML-ready editbox
   HTMLclassname = 'javax.swing.text.html.HTMLEditorKit';
   if ~isa(jEditbox.getEditorKit,HTMLclassname)
      jEditbox.setContentType('text/html');
   end
 
   % Parse the severity and prepare the HTML message segment
   if nargin < 3,  severity='info';  end
   switch lower(severity(1))
      case 'i',  icon = 'greenarrowicon.gif'; color='gray';
      case 'w',  icon = 'demoicon.gif';       color='black';
      otherwise, icon = 'warning.gif';        color='red';
   end
   icon = fullfile(matlabroot,'toolbox/matlab/icons',icon);
   iconTxt =['<img src="file:///',icon,'" height=16 width=16/>'];
   msgTxt = ['&nbsp;<font color=',color,'>',text,'</font>'];
   newText = [iconTxt,msgTxt];
   endPosition = jEditbox.getDocument.getLength;
   if endPosition>0, newText=['<br />' newText];  end
 
   % Place the HTML message segment at the bottom of the editbox
   currentHTML = char(jEditbox.getText);
   jEditbox.setText(strrep(currentHTML,[60 '/body>'],newText));
   endPosition = jEditbox.getDocument.getLength;
   jEditbox.setCaretPosition(endPosition); % end of content
end

Next, we initialize the log panel editbox and store the editbox’s underlying Java component (jEditbox) using the findjobj utility:

% Prepare the log editbox
hLogPanel = uicontrol('style','edit', 'max',5, 'Parent',hLeftBottomPanel, 'Units','norm', 'Position',[0,0.2,1,0.8], 'Background','w');
 
% Get the underlying Java editbox, which is contained within a scroll-panel
jScrollPanel = findjobj(hLogPanel);
try
    jScrollPanel.setVerticalScrollBarPolicy(jScrollPanel.java.VERTICAL_SCROLLBAR_AS_NEEDED);
    jScrollPanel = jScrollPanel.getViewport;
catch
    % may possibly already be the viewport, depending on release/platform etc.
end
jEditbox = handle(jScrollPanel.getView,'CallbackProperties');

Now, we can use this logging utility function to log messages in our application. For example:

logMessage(jEditbox, 'a regular info message...');
logMessage(jEditbox, 'a warning message...', 'warn');
logMessage(jEditbox, 'an error message!!!', 'error');
logMessage(jEditbox, 'a regular message again...', 'info');

Rich editbox contents (a log file)

Rich editbox contents (a log file)

HTML editboxes are normally editable, images included. In actual applications, we usually wish to prevent editing the displayed log. To do this, we simply call jEditbox.setEditable(false). Similarly, it is easy to set-up a Matlab callback-function to handle hyperlink clicks in the log panel (unlike what we might think, this is not handled automatically by the HTML processing engine):

% Prevent user editing in the log-panel
jEditbox.setEditable(false);
 
% Set-up a Matlab callback function to handle hyperlink clicks
set(jEditbox,'HyperlinkUpdateCallback',@linkCallbackFcn);

About the MATLAB Computational Finance Virtual Conference and my presentation

The MATLAB Computational Finance Virtual Conference is a one-day (Thursday Sep 19, 2013) event of hour-long presentations by industry professionals that showcase real-world examples demonstrating how financial-industry researchers and developers can excel at their jobs, improve their research and business processes, reduce costs, and mitigate risks by using Matlab. Registration to the conference is free and it’s a virtual conference, so there’s no need for a tie and jacket and you’re welcome to join…

MATLAB Computational Finance Conference 2013

My presentation on “A Real-Time Trading System in MATLAB“, is scheduled for 2pm EST / 8pm CEST. Following a half-hour presentation, I will answer audience questions online. The presentation slides can be downloaded here. Here is the recorded presentation video:

The demo system’s user interface showcases the hidden visualization and interactivity potential of Matlab for tracking order executions and charting financial time-series in real time. The undocumented features used in the demo include:

So, even if you’re not interested in real-time financial trading with Matlab, you might find it interesting to see the neat things that Matlab can do using a Java API interface and a few undocumented GUI tricks (such as the rich-contents log that I explained above).

The demo source code is provided here (tradingDemo.m and supporting files). Note that this is provided as-is, free of charge but without any warranty or support. You would naturally need IB-Matlab and an Interactive Brokers account to run it. But you can reuse parts of the source code in your Matlab programs even without an IB account or IB-Matlab.

]]>
https://undocumentedmatlab.com/blog_old/rich-contents-log-panel/feed 15
Real-time trading system demohttps://undocumentedmatlab.com/blog_old/real-time-trading-system-demo https://undocumentedmatlab.com/blog_old/real-time-trading-system-demo#comments Wed, 29 May 2013 13:15:21 +0000 https://undocumentedmatlab.com/?p=3825 Related posts:
  1. Uitable customization report Matlab's uitable can be customized in many different ways. A detailed report explains how. ...
  2. Uitable cell colors A few Java-based customizations can transform a plain-looking data table into a lively colored one. ...
  3. GUI integrated browser control A fully-capable browser component is included in Matlab and can easily be incorporated in regular Matlab GUI applications. This article shows how....
  4. Uitab colors, icons and images Matlab's semi-documented tab panels can be customized using some undocumented hacks...
]]>
Last week I gave a presentation at the MATLAB Computational Finance Conference in New York. The room was packed-full with close to 200 professionals in the finance industry. The energy and feedback were tremendous, it was a great experience. The presentation (PDF format) is provided here.

I presented a demo application that showed how Matlab can be used to create a full end-to-end trading system, highlighting Matlab’s potential as a platform of choice. I used Interactive Brokers to demonstrate live market data feed and account/portfolio input, as well as for sending trading orders to the market, via the IB-Matlab connector:

Real-time trading system demo in Matlab (click for details)

Real-time trading system demo in Matlab (click for details)

The demo system’s user interface showcased the hidden visualization and interactivity potential of MATLAB for tracking order executions and charting financial time-series in real time. The undocumented features used in the demo include:

The demo source code is provided here (tradingDemo.m and supporting files). Note that this is provided as-is, free of charge but without any warranty or support. You would naturally need IB-Matlab and an Interactive Brokers account to run it.

If you came to the conference, I want to thank you for being an excellent audience. I hope we have a chance to work together on your projects. Shoot me an email if you’d like my help in any consulting, training or development work.

]]>
https://undocumentedmatlab.com/blog_old/real-time-trading-system-demo/feed 1
Displaying animated GIFshttps://undocumentedmatlab.com/blog_old/displaying-animated-gifs https://undocumentedmatlab.com/blog_old/displaying-animated-gifs#comments Wed, 22 May 2013 18:00:38 +0000 https://undocumentedmatlab.com/?p=3772 Related posts:
  1. Spicing up Matlab uicontrol tooltips Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...
  2. Multi-line uitable column headers Matlab uitables can present long column headers in multiple lines, for improved readability. ...
  3. Rich-contents log panel Matlab listboxes and editboxes can be used to display rich-contents HTML-formatted strings, which is ideal for log panels. ...
  4. Aligning uicontrol contents Matlab uicontrols can often be customized using plain HTML/CSS, without need for advanced Java. ...
]]>
Displaying images in Matlab figures has always been sort-of awkward. We need to read the image file into a Matlab matrix (possibly with accompanying colormap), then create an invisible axis in our figure window, and finally display the image data within this axis, typically with the imagesc function. In practice, this is not as difficult as it may seem, and can be done in 3 lines of code (imread(); axes(); imagesc();). To display images in uicontrols, we need to set their CData property with the image data. Unfortunately, this is only supported for static (non-animated) images.

But what if we want to display an animated image? There are several image formats that enable animation, GIF being the most well-known. Animated GIFs are used ubiquitously, for anything from logos to simple visualizations. I often use them myself in my utilities and this blog, to illustrate functionality or usage. Creating animated GIFs is so easy — I often use Picasion, but there are numerous alternatives.

So let’s assume that I have the animated GIF featured here:

animated GIF

animated GIF

This example serves as the logo in a demo live trading application that I’ll present tomorrow at the MATLAB Computational Finance Conference.

To display this image in a Matlab GUI, we could use a mini-browser control that we can easily integrate within the figure. But an even simpler and less resource-intensive solution is to integrate an HTML panel:

hFig = figure('Color','w'); 
je = javax.swing.JEditorPane('text/html', '<html><img src="file:/C:\Yair\animated.gif"/></html>');
[hj, hc] =  javacomponent(je,[],hFig);
set(hc, 'pos', [10,10,70,70])

Animated GIF image integrated in Matlab figure

Animated GIF image integrated in Matlab figure


Notes:

  1. Although the GIF image is 64×64 pixels, we set the containing JEditorPane‘s size to 70×70, to account for the border and a small margin. You can obviously play with the size.
  2. The image source was specified using the file:/ protocol, as I explained here.

If our animated GIF uses transparency, we should set the container’s background to the same color as the figure, as I explained here:

bgcolor = num2cell(get(hFig,'Color'));
hj.setBackground(java.awt.Color(bgcolor{:}));

Animated transparent GIF image integrated in Matlab figure

Animated transparent GIF image integrated in Matlab figure

For anyone wondering, we could just as easily have used a simple JLabel rather than a JEditorPane (see here). The only difference is that we would need to also take care of the background:

hFig = figure('Color','w');
je = javax.swing.JLabel('<html><img src="file:/C:\Yair\animated.gif"/></html>');
je.setBackground(java.awt.Color(1,1,1));  %=white
[hj, hc] =  javacomponent(je,[],hFig);
set(hc, 'pos', [10,10,70,70])

We can similarly display animated GIFs on any uicontrol, due to the inherent nature of uicontrols that they accept HTML contents. So, we can place our animated GIF in buttons, drop-downs, listboxes etc. It’s not as straight-forward in drop-downs/listboxes as it is in buttons, but then again not many people need animated images in drop-downs or listboxes as they do in buttons. For push/toggle buttons, checkboxes and radio-buttons, displaying animated GIFs is trivially simple:

h1 = uicontrol('style','push',  'pos', [10,10,70,70], 'String','<html><img src="file:/C:\Yair\animated.gif"/></html>');
h2 = uicontrol('style','check', 'pos', [90,10,70,70], 'String','<html><img src="file:/C:\Yair\animated.gif"/></html>');
h3 = uicontrol('style','radio', 'pos',[170,10,70,70], 'String','<html><img src="file:/C:\Yair\animated.gif"/></html>');

Animated transparent GIF image integrated in Matlab uicontrols

Animated transparent GIF image integrated in Matlab uicontrols

The standard documented manner of displaying animated GIFs in Matlab is to imread all image frames from the GIF file, then start a timer that will periodically replace the axes image (or uicontrol CData property) with the next image frame in an endless loop. This is relatively tedious to set up, results in noticeable flicker and is relatively CPU intensive. I believe that the undocumented mechanism I’ve explained above is simpler to code and lighter on graphic resources.

Today’s article was a tribute to two old friends, whom I never met in person so far: a client who has recently asked me about this issue, and a member of a Graphics team who said he liked my related posts. I hope to meet both of them at the conference tomorrow. If you are interested in any aspect of computational finance, you will surely find some interesting presentations at this conference. So if you’re in town, I urge you to attend (free registration; my presentation is scheduled for 4:50pm). Otherwise, we could meet anywhere in New York tomorrow (Friday May 24), to discuss how I could bring value to your needs, either financial-oriented or not.

Matlab Computational Finance Conference - 23 May 2013

]]>
https://undocumentedmatlab.com/blog_old/displaying-animated-gifs/feed 16
Images in Matlab uicontrols & labelshttps://undocumentedmatlab.com/blog_old/images-in-matlab-uicontrols-and-labels https://undocumentedmatlab.com/blog_old/images-in-matlab-uicontrols-and-labels#comments Wed, 17 Oct 2012 18:00:57 +0000 https://undocumentedmatlab.com/?p=3177 Related posts:
  1. Rich-contents log panel Matlab listboxes and editboxes can be used to display rich-contents HTML-formatted strings, which is ideal for log panels. ...
  2. Spicing up Matlab uicontrol tooltips Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...
  3. Multi-line tooltips Multi-line tooltips are very easy to set up, once you know your way around a few undocumented hiccups....
  4. Multi-line uitable column headers Matlab uitables can present long column headers in multiple lines, for improved readability. ...
]]>
A couple of weeks ago, a reader here asked how to integrate images in Matlab labels. I see quite a few queries about this, so I wanted to take today’s opportunity to explain how this can be done, and how to avoid common pitfalls.

In fact, there are two main methods of displaying images in Matlab GUI – the documented method, and the undocumented one:

The documented method

Some Matlab uicontrols (buttons, radio and checkboxes) have the CData property that can be used to load and display an image. For example:

imgData = imread('myImage.jpg');   % or: imread(URL)
hButton = uicontrol('CData',imgData, ...);

While label uicontrols (uicontrol(‘style’,’text’, …)) also have the CData property, it has no effect on these controls. Instead, we can create an invisible axes that displays the image using the image function.

The undocumented method

web-based images

I’ve already written extensively about Matlab’s built-in support for HTML in many of its controls. The supported HTML subset includes the <img> tag, and can therefore display images. For example:

htmlStr = '<html><b>Logo</b>: <img src="https://undocumentedmatlab.com/images/logo_68x60.png"/></html>';
hButton = uicontrol('Position',[10,10,120,70], 'String',htmlStr, 'Background','white');

uicontrol with HTML image

uicontrol with HTML image

local images

Note that the image src (filename) needs to be formatted in a URL-compliant format such as 'http://www.website.com/folder/image.gif' or 'file:/c:/folder/subfolder/img.png'. If we try to use a non-URL-format filename, the image will not be rendered, only a placeholder box:

uicontrol('Position',..., 'String','<html><img src="img.gif"/></html>');  %bad
uicontrol('Style','list', ... 'String',{...,'<html><img src="img.gif"/></html>'});  %bad

Ill-specified HTML images in Matlab uicontrols Ill-specified HTML images in Matlab uicontrols

Ill-specified HTML images in Matlab uicontrols

Instead, we need to use correct URI syntax when specifying local images, which means using the 'file:/' protocol prefix and the '/' folder separator:

>> iconsFolder = fullfile(matlabroot,'/toolbox/matlab/icons/');
>> iconUrl = strrep(['file:/' iconsFolder 'matlabicon.gif'],'\','/');
>> str = ['<html><img src="' iconUrl '"/></html>']
str =
<html><img src="file:/C:/Program Files/MATLAB/ ..... /icons/matlabicon.gif"/></html>
 
>> uicontrol('Position',..., 'String',str);
>> uicontrol('Style','list', ... str});

Correctly-specified HTML images in Matlab uicontrols Correctly-specified HTML images in Matlab uicontrols

Correctly-specified HTML images in Matlab uicontrols

A similar pitfall exists when trying to integrate images in GUI control tooltips. I already discussed this issue here.

You can use HTML to resize the images, using the <img> tag’s width, height attributes. However, beware that enlarging an image might introduce pixelization effects. I discussed image resizing here – that article was in the context of menu-item icons, but the discussion of image resizing also applies in this case.

images in text labels

As for text labels, since text-style uicontrols do not unfortunately support HTML, we can use the equivalent Java JLabels, as I have explained here. Here too, we need to use the 'file:/' protocol prefix and the '/' folder separator if we want to use local files rather than internet files (http://…).

Java customizations

Using a uicontrol’s underlying Java component, we can customize the displayed image icon even further. For example, we can specify a different icon for selected/unselected/disabled/hovered/pressed/normal button states, as I have explained here. In fact, we can even specify a unique icon that will be used for the mouse cursor when it hovers on the control:

Custom cursor Custom cursor

Custom uicontrol cursors

]]>
https://undocumentedmatlab.com/blog_old/images-in-matlab-uicontrols-and-labels/feed 28
Bold color text in the Command Windowhttps://undocumentedmatlab.com/blog_old/bold-color-text-in-the-command-window https://undocumentedmatlab.com/blog_old/bold-color-text-in-the-command-window#comments Wed, 08 Aug 2012 18:00:34 +0000 https://undocumentedmatlab.com/?p=3052 Related posts:
  1. Customizing help popup contents The built-in HelpPopup, available since Matlab R2007b, has a back-door that enables displaying arbitrary text, HTML and URL web-pages....
  2. setPrompt – Setting the Matlab Desktop prompt The Matlab Desktop's Command-Window prompt can easily be modified using some undocumented features...
  3. Customizing Workspace context-menu Matlab's Workspace table context-menu can be configured with user-defined actions - this article explains how....
  4. Variables Editor scrolling The Matlab Variables Editor can be accessed to provide immediate scrolling to a specified cell location. ...
]]>
A reader comment last week sent me on a short wild goose chase, that had an interesting and useful conclusion. The comment requested a way to display bold text in the Command Window, similarly to the way that we can display colored and underlined text using my cprintf utility.

Since Matlab release 7.13 (R2011b), the Matlab Command Window (CW) has the ability to display bold text. This is used, for example, when displaying the function name in the output of the help function (i.e., help(‘max’) will display the term ‘max’ in bold when displaying the help section). It therefore seemed a reasonable request to add this functionality to cprintf.

Attempt #1: use the underlying Java

I stated out investigating the relevant attributes used by the CW’s underlying Java component to display the text. It turns out that in addition to the three custom attributes used by Matlab in past releases, a fourth attribute called BoldStartTokens was added, which stored the relative position index of the bold text within each text element.

Unfortunately, this attribute contains an array of integer values, that get converted to a simple numeric array in Matlab. This means that unlike the SyntaxTokens attribute, which contains an array of Java String objects that can be modified one at a time (this is used by cprintf), the BoldStartTokens attribute value cannot be modified in a similar manner. Attempting to remove and add the attribute afresh (with modified values) failed due to a javax.swing.text.StateInvariantError: Illegal cast to MutableAttributeSet Java exception.

So unless I find a way to update the BoldStartTokens attribute values from Matlab, this looked like a dead end.

Attempt #2: follow the Matlab trail

My second attempt was to follow the Matlab trail, to see exactly what the help function does internally to format parts of the text as bold. Starting with help‘s m-file (%matlabroot%/toolbox/matlab/helptools/help.m), and step-by-step debugging, I quickly found out that the internal function prepareHelpForDisplay parses the help text and wraps the relevant terms with an HTML <strong> tag to make these terms appear bold.

We can easily use this information ourselves:

>> fprintf('not bold, <strong> bold </strong>\n')
not bold, bold     % the 'bold' term appears bolded

Matlab does have an internal limitation, of not allowing hyperlinks and bold formatting together. If both <a> and <strong> tags are present, then only the inner tag set is parsed.

Updating cprintf

Using <strong> is great, but apparently if we use the <strong> tag in cprintf, the output gets messed up – the HTML tag confuses cprintf. So I took the opportunity to update cprintf such that (1) it will not get confused by a <strong> tag, and (2) so that we could use ‘*’ in the style part (input argument #1) to specify bold format:

>> cprintf('*blue', 'this is bold\n')
this is bold     % this text appears bolded-blue

cprintf demo

cprintf demo


The benefit of using cprintf over directly using the <strong> tag is that it works seamlessly on Matlab release 2011a and earlier that do not support the tag (the text is simply not bolded, whereas if we had used <strong> this tag would be displayed onscreen, which is ugly). Moreover, cprintf catches a situation of trying to use both underline and bold formats, and issues a warning. Finally, of course, ‘*’ is more compact and easier to use and maintain than ‘<strong>…</strong>’ …

Please feel free to download cprintf from the File Exchange and read its contents to see how a not-too-large utility can achieve something previously believed to be impossible. And if you find ways to make cprintf better, please do let me know (I don’t mean suggestions for *me* to work on: I mean actual improvements that *you* made to the code).

]]>
https://undocumentedmatlab.com/blog_old/bold-color-text-in-the-command-window/feed 3
Multi-line uitable column headershttps://undocumentedmatlab.com/blog_old/multi-line-uitable-column-headers https://undocumentedmatlab.com/blog_old/multi-line-uitable-column-headers#comments Wed, 27 Jun 2012 22:54:40 +0000 https://undocumentedmatlab.com/?p=2976 Related posts:
  1. Spicing up Matlab uicontrol tooltips Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...
  2. Rich-contents log panel Matlab listboxes and editboxes can be used to display rich-contents HTML-formatted strings, which is ideal for log panels. ...
  3. Aligning uicontrol contents Matlab uicontrols can often be customized using plain HTML/CSS, without need for advanced Java. ...
  4. Displaying animated GIFs It is possible to easily display animated images in Matlab figure windows. ...
]]>
I often need to present data in tabular format in Matlab GUI, and this data often has relatively long column headers such as “Maximal draw/gain” or “Coefficient of elasticity”. When the table has many columns, these long column headers do not fit in the small space that is available:

uitable('data',magic(2),'ColumnName',{'Maximal draw/gain','Coefficient of elasticity'})

Default uitable behavior with long headers

Default uitable behavior with long headers

Creating multi-line headers

It makes sense to split such long column headers into a multi-line string. In the new (R2008a+) uitable, this can easily be done by adding the | character wherever we wish the line to be split; in both the new and the old uitable, we can also use the built-in HTML support by adding a simple <br/>. The following code snippet demonstrates both of these alternatives:

uitable('data',magic(2), 'ColumnName',{'Maximal|draw/gain', '<html><center />Coefficient<br />of elasticity</html>'});

Multi-line uitable headers

Multi-line uitable headers

Much more readable and useful, I think. Note that HTML code is left-aligned by default, so to center the header I added the <center> tag in the snippet.

If the text appears too crowded in the header cells, we can slightly reduce the header font, to make it appear more spaced-out. The following snippet illustrates this for the old uitable (available since Matlab 7.0 all the way until today), which can only use the HTML alternative since it does not support |:

headers = {'<html>Maximal<br />draw/gain</html>', ...
           '<html><center /><font size=-2>Coefficient<br />of elasticity</font></html>'};
uitable('v0','data',magic(2),'ColumnNames',headers);

Multi-line headers in the old uitable

Multi-line headers in the old uitable

Dynamic multi-line headers

While adding | or <br/> solves the problem for the majority of cases, it is sometimes difficult to know in advance where to place the line-split. This often happens when the column headers are dynamically generated by the program. If we omit the <br/> from our header strings, we get sub-optimal rendering: The new uitable simply hides all overflow terms, and the old uitable pushes them to the bottom:

headers = {'<html>Maximal draw/gain</html>', ...
           '<html><center /><font size=-2>Coefficient of elasticity</font></html>'};
uitable('v0','data',magic(2),'ColumnNames',headers);

Default dynamic HTML multi-line (old uitable)

Default dynamic HTML multi-line (old uitable)

I’ve tried numerous things, including CSS wrapping directives etc. None seem to work (I’ll be happy to hear a new idea that does work), except for the following weird-sounding trick: add a “<br/>&nbsp;” at the end of the HTML header string. If the column is wide enough, then this will be disregarded; otherwise, it will automatically split the string nicely:

headers = {'<html>Maximal draw/gain<br />&nbsp;</html>', ...
           '<html><center /><font size=-2>Coefficient of elasticity<br />&nbsp;</font></html>'};
uitable('v0','data',magic(2),'ColumnNames',headers);

Nicely-behaved dynamic HTML multi-lines

Nicely-behaved dynamic HTML multi-lines

Note: the &nbsp; part is important – the trick will NOT work without it!

Controlling the headers

HTML provides some degree of control over the table header row. Some additional aspects can be configured by accessing the underlying Java’s TableHeader sub-component. But here’s another trick that I found handy: I hide the table header row altogether, and use the top table data row for my headers. I can control this row’s height using JTable’s standard setRowHeight() method. Using some fancy cell background colors I can make this row stand out, and I can easily control other aspects as well.

The same trick can also be used for the row-header column: I can dispense with the standard one and use the table’s first column as a row-header column.

For more information on uitable customization, refer to section 4.1 of my Matlab-Java book, or to my uitable customization report.

Do you have a favorite trick with multi-line strings in Matlab GUI? If so, please share it in a comment below.

]]>
https://undocumentedmatlab.com/blog_old/multi-line-uitable-column-headers/feed 19
Customizing menu items part 1https://undocumentedmatlab.com/blog_old/customizing-menu-items-part-1 https://undocumentedmatlab.com/blog_old/customizing-menu-items-part-1#comments Wed, 25 Apr 2012 18:14:08 +0000 https://undocumentedmatlab.com/?p=2897 Related posts:
  1. Tab panels – uitab and relatives This article describes several undocumented Matlab functions that support tab-panels...
  2. Context-Sensitive Help Matlab has a hidden/unsupported built-in mechanism for easy implementation of context-sensitive help...
  3. Undocumented mouse pointer functions Matlab contains several well-documented functions and properties for the mouse pointer. However, some very-useful functions have remained undocumented and unsupported. This post details their usage....
  4. Matlab layout managers: uicontainer and relatives Matlab contains a few undocumented GUI layout managers, which greatly facilitate handling GUI components in dynamically-changing figures....
]]>
Over the past years, I have not posted articles dealing with menu items. I have shown how to directly access menu items’ hidden handles, but not much more than that. A year ago I promised a mini-series on menu customizations, and it’s time to keep my promise. In today’s article, the first in the mini-series, I will present several undocumented menu customization topics that rely on pure-Matlab (i.e, no Java today). The next article in this series will focus on Java-based customizations.

Invoking menu item callbacks

As noted above, a figure window’s menu items can be directly accessed. Once we access a menu item’s handle, we can extract its Callback property and directly invoke it (for example, using the semi-documented hgfeval function). Note that menu callbacks are kept in Callback, while toolbar callbacks are kept in ClickedCallback.

Menu callbacks generally use internal semi-documented functions (i.e., having a readable help section but no doc, online help, or official support), which are part of Matlab’s uitools folder. These functions are specific to each top-level menu tree: filemenufcn, editmenufcn, viewmenufcn, insertmenufcn, toolsmenufcn, desktopmenufcn, winmenu, and helpmenufcn implement the figure’s eight respective top-level menu trees’ callbacks. These functions accept an optional figure handle (otherwise, gcbf is assumed), followed by a string specifying the specific menu item whose action needs to be run. webmenufcn implements the Help menu’s Web Resources sub-menu callbacks in a similar manner.

Use of these functions makes it easy to invoke a menu action directly from our Matlab code: instead of accessing the relevant menu item and invoking its Callback, we simply find out the menu item string in advance and use it directly. For example,

filemenufcn FileClose;
editmenufcn(hFig,'EditPaste');

uimenufcn is a related fully-undocumented (built-in) function, available since Matlab R11 (late 1990s). It accepts a figure handle (or the zero [0] handle to indicate the desktop) and action name. For example, the fully-documented commandwindow function uses the following code to bring the Command Window into focus:

uimenufcn(0, 'WindowCommandWindow');

Customizing menus via uitools

makemenu is another semi-documented uitool function that enables easy creation of hierarchical menu trees with separators and accelerators. It is a simple and effective wrapper for uimenu. makemenu is a useful function that has been made obsolete (grandfathered) without any known replacement.

makemenu accepts four parameters: a figure handle, a char matrix of labels (‘>’ indicating sub item, ‘>>’ indicating sub-sub items etc.; ‘&’ indicating keyboard shortcut; ‘^x’ indicating an accelerator key; ‘-‘ indicating a separator line), a char matrix of callbacks, and an optional char matrix of tags (empty by default). makemenu makes use of another semi-documented grandfathered function, menulabel, to parse the specified label components. makemenu returns an array of handles of the created uimenu items:

labels = str2mat('&File', ...    % File top menu
           '>&New^n', ...           % File=>New
           '>&Open', ...            % File=>Open
           '>>Open &document^d', ...    % File=>Open=>doc
           '>>Open &graph^g', ...       % File=>Open=>graph
           '>-------', ...          % File=>separator line
           '>&Save^s', ...          % File=>Save
           '&Edit', ...		% Edit top menu
           '&View', ...		% View top menu
           '>&Axis^a', ...          % View=>Axis
           '>&Selection region^r'); % View=>Selection
calls = str2mat('', ...		% no action: File top menu
           'disp(''New'')', ...
           '', ...			% no action: Open sub-menu
           'disp(''Open doc'')', ...
           'disp(''Open graph'')', ...
           '', ...			% no action: Separator
           'disp(''Save'')', ...
           '', ...			% no action: Edit top menu
           '', ...			% no action: View top menu
           'disp(''View axis'')', ...
           'disp(''View selection region'')');
handles = makemenu(hFig, labels, calls);
set(hFig,'menuBar','none');

A simple figure menu

A simple figure menu

Customizing menus via HTML

Since menu items share the same HTML/CSS support feature as all Java Swing labels, we can specify font size/face/color, bold, italic, underline, superscript/subscript, and practically any HTML formatting.

Note that some features, such as the font or foreground/background colors, have specific properties that we can set using the Java handle, instead of using HTML. The benefit of using HTML is that it enables setting all the formatting in a single property. HTML does not require using Java – just pure Matlab (see the following example).

Multi-line menu items can easily be done with HTML: simply include a <br> element in the label – the menu item will split into two lines and automatically resize vertically when displayed:

txt1 = '<html><b><u><i>Save</i></u>';
txt2 = '<font color="red"><sup>this file</sup></font></b></html>';
txt3 = '<br />this file as...';
set(findall(hFig,'tag','figMenuFileSave'),   'Label',[txt1,txt2]);
set(findall(hFig,'tag','figMenuFileSaveAs'), 'Label',[txt1,txt3]);

A multi-line HTML-rendered menu item

A multi-line HTML-rendered menu item

set(hMenuItem, 'Label',['<html>&2: C:\My Documents\doc.txt<br />'
   '<font size="-1" face="Courier New" color="red">&nbsp;&nbsp; '
   'Date: 15-Jun-2011 13:23:45<br />&nbsp;&nbsp; Size: 123 KB</font></html>']);

HTML-rendered menu items

HTML-rendered menu items

Much more complex customizations can be achieved using Java. So stay tuned to part 2 of this mini-series…

Note: Menu customization is explored in depth in section 4.6 of my book.

]]>
https://undocumentedmatlab.com/blog_old/customizing-menu-items-part-1/feed 10
Multi-line tooltipshttps://undocumentedmatlab.com/blog_old/multi-line-tooltips https://undocumentedmatlab.com/blog_old/multi-line-tooltips#comments Thu, 03 Nov 2011 02:05:36 +0000 https://undocumentedmatlab.com/?p=2518 Related posts:
  1. Multi-line uitable column headers Matlab uitables can present long column headers in multiple lines, for improved readability. ...
  2. Images in Matlab uicontrols & labels Images can be added to Matlab controls and labels in a variety of manners, documented and undocumented. ...
  3. Displaying animated GIFs It is possible to easily display animated images in Matlab figure windows. ...
  4. HG2 update HG2 appears to be nearing release. It is now a stable mature system. ...
]]>
I often use tooltips in my Matlab GUIs. They are a fantastically intuitive and unobtrusive visual helper for users to understand the GUI. In this blog, I have already posted several articles about how to tweak tooltip contents (here, here, and here). Today I would like to expand on one of the aspects that were already covered, namely that of multi-line tooltips.

Basic multi-line tooltips

The basic multi-line tooltip consists of a simple string that includes the newline character. for example:

set(hControl, 'TooltipString', ['this is line 1' 10 'and this is line 2'])

Or better (platform independent):

set(hControl, 'TooltipString', sprintf('this is line 1\nand this is line 2'))

A simple multi-line tooltip string

A simple multi-line tooltip string

As can be seen, this is very simple to set up. Unfortunately, the font cannot be customized. Which leads us to:

HTML-rendered multi-line tooltips

Tooltips, like most other Matlab controls, supports HTML rendering. This is a natural corollary of the fact that Java Swing, on which all Matlab controls are based, automatically supports HTML. All we need to do is to add ‘<HTML>‘ at the very beginning of our tooltip string, and then we can embed HTML tags within the rest of the string:

set(hControl, 'tooltipString', '<html><b>line #1</b><br /><i><font color="red">line#2</font></i></html>');

Multi-line HTML'ed tooltip

Multi-line HTML'ed tooltip

And a more sophisticated example, used within my createTable utility on the File Exchange:

A more complex multi-line HTML-based tooltip

A more complex multi-line HTML-based tooltip

Note that there is no need to close the final HTML tags in the tooltip string, although it’s not an error to do so (as I have done above).

The problem with formatted multi-line tooltip

Unfortunately, none of these two methods work when we wish to display formatted multi-line tooltips. For example, suppose that we wish to display struct data in a tooltip:

>> myData = struct('a',pi, 'b',-4, 'very_long_field_name','short txt')
myData = 
                       a: 3.14159265358979
                       b: -4
    very_long_field_name: 'short txt'
 
>> myDataStr = evalc('disp(myData)');
>> set(hControl, 'TooltipString', myDataStr);

Badly-formatted multi-line tooltip

Badly-formatted multi-line tooltip

If we try to use HTML, the result looks even worse, because if the HTML-renderer detects a newline character embedded in the string, it simply uses the regular (non-HTML) renderer:

set(hControl, 'TooltipString', ['<html>' myDataStr '</html>'])

Failure to parse a string using HTML

Failure to parse a string using HTML

Even if we fix this by replacing all line-separators with ‘<br/>‘, we still get a badly-formatted tooltip, because HTML ignores all white spaces:

>> myDataStr2 = strrep(myDataStr, sprintf('\n'), '<br />');
>> set(hControl, 'TooltipString', ['<html>' myDataStr2 '</html>'])

Badly-formatted multi-line tooltip

Badly-formatted multi-line tooltip

(you can see that it’s HTML-formatted by the fact that the tooltip contents do not have internal margins like in the non-HTML tooltip above)

Fixed-width font multi-line tooltips

We now recall the HTML <pre> tag, which tells HTML not to ignore white-spaces. In most web browsers, it also defaults to using a fixed-width font. Unfortunately, this is not the case here:

set(hControl, 'TooltipString', ['<html><pre>' myDataStr2])

Still not quite right...

Still not quite right...

Which brings us to the final customization of the day, namely explicitly forcing the tooltip to use a fixed-width font:

set(hControl, 'TooltipString', ['<html><pre><font face="courier new">' myDataStr2 '</font>'])

Finally - a well-formatted multi-line tooltip

Finally - a well-formatted multi-line tooltip

Even more powerful customizations can be achieved using CSS rather than pure HTML. This will be discussed a future article.

]]>
https://undocumentedmatlab.com/blog_old/multi-line-tooltips/feed 5
Uitable cell colorshttps://undocumentedmatlab.com/blog_old/uitable-cell-colors https://undocumentedmatlab.com/blog_old/uitable-cell-colors#comments Thu, 27 Oct 2011 01:51:53 +0000 https://undocumentedmatlab.com/?p=2476 Related posts:
  1. Uitable customization report Matlab's uitable can be customized in many different ways. A detailed report explains how. ...
  2. Tri-state checkbox Matlab checkboxes can easily be made to support tri-state functionality....
  3. GUI integrated browser control A fully-capable browser component is included in Matlab and can easily be incorporated in regular Matlab GUI applications. This article shows how....
  4. Customizing listbox & editbox scrollbars Matlab listbox and multi-line editbox uicontrols have pre-configured scrollbars. This article shows how they can be customized....
]]>
A client recently asked me to develop an application that will help discover technical indicators for trading on the stock market. The application was very data-intensive and the analysis naturally required visual presentations of number-crunching results in a readable manner. One of the requirements was to present numeric results in a data table, so we naturally use uitable for this.

Today I will show how using some not-so-complex Java we can transform the standard Matlab uitable into something much more useful.

First pass – basic data table

We start by displaying the data in a simple uitable. The essence of the relevant code snippet was something like this:

headers = {'Periods', ...
           '<html><center>Any period<br />returns</center></html>', ...
           '<html><center>Avg return<br />signal</center></html>', ...
           '<html><center>Avg<br />gain</center></html>', ...
           '<html><center>Avg<br />draw</center></html>', ...
           '<html><center>Gain/draw<br />ratio</center></html>', ...
           '<html><center>Max<br />gain</center></html>', ...
           '<html><center>Max<br />draw</center></html>', ...
           '<html><center>Random<br />% pos</center></html>', ...
           '<html><center>Signal<br />% pos</center></html>', ...
           'Payout', '% p-value'};
hTable = uitable('Data',data, 'ColumnEditable',false, ...
           'ColumnName',headers, 'RowName',[], ...
           'ColumnFormat',['numeric',repmat({'bank'},1,11)], ...
           'ColumnWidth','auto', ...
           'Units','norm', 'Position',[0,.75,1,.25]);

Plain data table - so boooooring...

Plain data table - so boooooring...

We can see from this simple example how I have used HTML to format the header labels into two rows, to enable compact columns. I have already described using HTML formatting in Matlab controls in several articles on this website. I have not done this here, but you can easily use HTML formatting for other effect such as superscript (<sup>), subscript (<sub>), bold (<b>), italic (<i>), font sizes and colors (<font>) and other standard HTML effects.

Even with the multi-line headers, the default column width appears to be too wide. This is apparently an internal Matlab bug, not taking HTML into consideration. This causes only part of the information to be displayed on screen, and requires the user to either scroll right and left, or to manually resize the columns.

Second pass – auto-resizing that actually works…

To solve the auto-resizing issue, we resort to a bit of Java magic powder. We start by using the findjobj utility to get the table’s underlying Java reference handle. This is the containing scrollpane, and we are interested in the actual data table inside. We then use the setAutoResizeMode, as described in the official Java documentation.

jScroll = findjobj(hTable);
jTable = jScroll.getViewport.getView;
jTable.setAutoResizeMode(jTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);

Auto-resized columns that actually work

Auto-resized columns that actually work

Third pass – adding colors

There are still quite a few other customizations needed here: enable sorting; remove the border outline; set a white background; set row (rather than cell) selection and several other fixes that may seem trivial by themselves but together giver a much more stylish look to the table’s look and feel. I’ll skip these for now (interested readers can read all about them, and more, in my detailed uitable customization report).

One of the more important customizations is to add colors depending on the data. In my client’s case, there were three requirements:

  • data that could be positive or negative should be colored in green or red foreground color respectively
  • large payouts (abs > 2) should be colored in blue
  • data rows that have statistical significance (%p-value < 5) should have a yellow background highlight

While we could easily use HTML or CSS formatting to do this, this would be bad for performance in a large data table, may cause some issues when editing table cells or sorting columns. I chose to use the alternative method of cell renderers.

ColoredFieldCellRenderer is a simple table cell renderer that enables setting cell-specific foreground/background colors and tooltip messages (it also has a few other goodies like smart text alignment etc.). This requires some Java knowledge to program, but in this case you can simply download the ColoredFieldCellRenderer.zip file and use it, even if you don’t know Java. The source code is included in the zip file, for anyone who is interested.

After using javaaddpath to add the zip file to the dynamic Java classpath (you can add it to the static classpath.txt file instead), the contained Java class file is available for use in Matlab. We configure it according to our data and then assign it to all our table’s columns.

Java savvy readers might complain that the data-processing should perhaps be done in the renderer class rather than in Matlab. I have kept it in Matlab because this would enable very easy modification of the highlighting algorithm, without any need to modify the generic Java renderer class.

Unfortunately, in the new uitable design (the version available since R2008a), JIDE and Matlab have apparently broken the standard MVC approach by using a table model that not only controls the data but also sets the table’s appearance (row-striping background colors, for example), and disregards column cell-renderers. In order for our custom cell renderer to have any effect, we must therefore replace Matlab’s standard DefaultUIStyleTableModel with a simple DefaultTableModel. This in itself is not enough – we also need to ensure that the uitable has an empty ColumnFormat property, because if it is non-empty then it overrides our cell-renderer.

In the following code, note that Java row and column indices start at 0, not at 1 like in Matlab. We need to be careful about indices when programming java in Matlab.

The rest of the code should be pretty much self explanatory (again – more details can be found in the above-mentioned report):

% Initialize our custom cell renderer class object
javaaddpath('ColoredFieldCellRenderer.zip');
cr = ColoredFieldCellRenderer(java.awt.Color.white);
cr.setDisabled(true);  % to bg-color the entire column
 
% Set specific cell colors (background and/or foreground)
for rowIdx = 1 : size(data,1)
 
  % Red/greed foreground color for the numeric data
  for colIdx = 2 : 8
    if data(rowIdx,colIdx) < 0
      cr.setCellFgColor(rowIdx-1,colIdx-1,java.awt.Color(1,0,0));    % red
    elseif data(rowIdx,colIdx) > 0
      cr.setCellFgColor(rowIdx-1,colIdx-1,java.awt.Color(0,0.5,0));  % green
    end
  end
 
  % Yellow background for significant rows based on p-value
  if data(rowIdx,12) < = 5 && data(rowIdx,11)~=0
    for colIdx = 1 : length(headers)
      cr.setCellBgColor(rowIdx-1,colIdx-1,java.awt.Color(1,1,0));    % yellow
    end
  end
 
  % Bold blue foreground for significant payouts
  if abs(data(rowIdx,11)) >= 2
    cr.setCellFgColor(rowIdx-1,10,java.awt.Color(0,0,1));    % blue
 
    % Note: the following could easily be done in the renderer, just like the colors
    boldPayoutStr = ['<html><b>' num2str(data(rowIdx,11),'%.2f') '</b></html>'];
    %jTable.setValueAt(boldPayoutStr,rowIdx-1,10);  % this is no good: overridden when table model is replaced below...
    dataCells{rowIdx,11} = boldPayoutStr;
  end
end
 
% Replace Matlab's table model with something more renderer-friendly...
jTable.setModel(javax.swing.table.DefaultTableModel(dataCells,headers));
set(hTable,'ColumnFormat',[]);
 
% Finally assign the renderer object to all the table columns
for colIdx = 1 : length(headers)
  jTable.getColumnModel.getColumn(colIdx-1).setCellRenderer(cr);
end

Finally something lively!

Finally something lively!

This may not take a beauty contest prize, but you must admit that it now looks more useful than the original table at the top of this article.

]]>
https://undocumentedmatlab.com/blog_old/uitable-cell-colors/feed 115
Uitable customization reporthttps://undocumentedmatlab.com/blog_old/uitable-customization-report https://undocumentedmatlab.com/blog_old/uitable-customization-report#comments Wed, 03 Aug 2011 18:00:25 +0000 https://undocumentedmatlab.com/?p=2396 Related posts:
  1. Uitable sorting Matlab's uitables can be sortable using simple undocumented features...
  2. Date selection components The JIDE package, pre-bundled in Matlab, contains several GUI controls for selecting dates - this article explains how they can be used...
  3. Tri-state checkbox Matlab checkboxes can easily be made to support tri-state functionality....
  4. Font selection components Several built-in components enable programmatic font selection in Matlab GUI - this article explains how. ...
]]>
In last week’s report about uitable sorting, I offered a report that I have written which covers uitable customization in detail. Several people have asked for more details about the contents of this report. This is a reasonable request, and so in today’s post I will discuss in a bit more detail the highlights of what can be achieved to customize Matlab uitables. For the fine details, well, get my uitable report (45 pages PDF, $25).

1. Introduction

Here I discuss the evolution of the uitable control over the past decade, from its initially semi-documented status to today. I explain the similarities and differences between the control’s versions and explain how they can both be accessed today.

I also provide references to online resources for both Matlab’s uitable‘s underlying Java components, as well as multiple alternatives using different technologies, that have been used and reported over the years.

2. Customizing uitable

In this section I explore the sub-component hierarchy of the uitable controls. I show how the scrollbar sub-components can be accessed (this will be used in section 4 below), as well as the table header and data grid. This is the entry point for uitable customization.

annotated uitable sub-components

annotated uitable sub-components

I explain how individual cells can be modified without requiring the entire data set to be updated. This is very important in large data sets, to prevent flicker and improve performance.

I show how HTML can be used to format data cell contents (even images) and tooltips:

uitable with HTML cell contents and tooltip

uitable with HTML cell contents and tooltip


uitable with cell images

uitable with cell images

3. Cell renderers and cell editors

This section explains the role of the cell-renderer in the visual appearance of the cell, and of cell-editors in the way that cells interact with the user for data modification. I explain such customizations from the simple (setting a column’s background color) to the complex (cell-specific tooltips and colors; color-selection cell-editor):


uitable with a non-standard cell-renderer

uitable with a non-standard cell-renderer


uitable with a non-standard cell-rendereruitable with a non-standard cell-editor

uitable with a non-standard cell-renderer (left) and cell-editor (right)


uitable with custom CellRenderer and CellEditor

uitable with custom CellRenderer and CellEditor

Cell renderers can also be used to set custom text format of cell contents and cell-specific tooltips (note the top table in the following screenshot):

uitable with custom CellRenderers (note text formats and cell-specific tooltips)

uitable with custom CellRenderers (note text formats and cell-specific tooltips)


(also note the colored table headers in the bottom table)

4. Table callbacks

This section of my uitable report presents the different callback properties that are settable in the old and new uitable, for events such as cell selection, data modification, key press, and mouse click. The discussion includes a working code example for validating user input and reverting invalid edits. The section also includes a discussion of how to avoid and overcome problems that may occur with the callback execution.

5. Customizing scrollbars, column widths and selection behavior

This section explains how to control the scrollbars behavior. For example, hiding the horizontal (bottom) scrollbar, automatically displaying it when the data width is larger than the table width. I also show how to control the column widths.

I then show how to customize the data selection policy: Can multiple cells be selected? perhaps only one cell at a time? or maybe a single large interval of cells? – this is all customizable. I then explain how the selection can be done and accessed programmatically. Ever wanted to set the cursor on cell A1 after some system event has occurred? – this will show you how to do it. Ever wanted to use non-standard selection colors (background/foreground)? – this can also be done.

6. Data sorting

Table sorting was discussed in last week’s article. This section expands on that article, and explains how the sorting can be customized, controlled, and accessed programmatically, and how sorted rows can be retrieved by the user.

Multi-column sorting with blue sort-order numbers

Multi-column sorting with blue sort-order numbers

7. Data filtering

Data filtering is the ability to filter only a specified sub-set of rows for display (just like in Excel). This section explains how to do it (it’s so easy!).

uitable data filtering

uitable data filtering

8. JIDE customizations

The new uitable is based on an underlying JIDE table. This sectino explains how we can use this to our advantage for some simple and useful. Customization.

For example: have you wondered some time why is it that columns can only be resized by dragging the tiny divider in the table header? Why can’t the columns and rows be resized by dragging the grid lines? Well, it turns out that they can, with just a tiny bit of JIDE magic powder, explained here:

Resizing columns

Resizing columns

Similarly, this section explains how we can use JIDE to merge together adjacent cells:

Example of two table cell-spans (1x2 and 2x2)

Example of two table cell-spans (1x2 and 2x2)

I also show how to attach a custom context-menu (right-click menu) to the table header row:

Custom header-row context-menu

Custom header-row context-menu

9. Controlling the table structure (adding/removing rows)

This section discusses the matter of dynamically adding and removing table rows. While this is easy to do in the old uitable, this is unfortunately not the case in the new uitable.

10. Run-time performance

This section discusses ways to improve the run-time performance (speed) of uitable, both new and old. For additional information regarding run-time performance, refer to my book “MATLAB Performance Tuning“.

11. Final remarks

Here I present a workaround for a long-time table bug. Also, I present my createTable utility that wraps table creation in Matlab:

createTable utility screenshot (note the action buttons, sortable columns, and customized CellEditor)

createTable utility screenshot (note the action buttons, sortable columns, and customized CellEditor)

Appendix – JIDE Grids

Finally, this appendix presents an overview of the wide array of components provided by JIDE and available in Matlab. uitable uses only one of these components (the SortableTable). In fact, there are many more such controls that we can use in our GUIs.

These include a wide selection of combo-box (drop-down) controls – calculator, file/folder selection, date selection, color selection, multi-elements selection etc.

Date selection comb-box

Date selection combo-box

In addition, a very wide selection of lists, trees and table types is available.

TreeTable example

TreeTable example

Also included is a set of specialized editbox controls for accepting IP addresses and credit card numbers:

IP address entry boxcredit-card entry boxcredit-card entry box

IP address and credit-card entry boxes

While not explaining all these controls in detail (this could take hundreds of pages), this section does say a few words on each of them, and includes links to online resources for further exploration.

]]>
https://undocumentedmatlab.com/blog_old/uitable-customization-report/feed 74
Uitable sortinghttps://undocumentedmatlab.com/blog_old/uitable-sorting https://undocumentedmatlab.com/blog_old/uitable-sorting#comments Tue, 26 Jul 2011 18:00:01 +0000 https://undocumentedmatlab.com/?p=2391 Related posts:
  1. Uitable customization report Matlab's uitable can be customized in many different ways. A detailed report explains how. ...
  2. Tab panels – uitab and relatives This article describes several undocumented Matlab functions that support tab-panels...
  3. treeTable A description of a sortable, groupable tree-table control that can be used in Matlab is provided. ...
  4. Types of undocumented Matlab aspects This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...
]]>
uitable is probably the most complex basic GUI controls available in Matlab. It displays data in a table within a figure, with settable properties as with any other Matlab Handle-Graphics (HG) control. After many years in which the uitable was available but semi-documented and not officially supported in Matlab, it finally became fully documented and supported in R2008a (aka Matlab 7.6). At that time its internal implementation has changed from a MathWorks-developed Java table to a JIDE-based Java table (another JIDE-derived table was described here last year). Since R2008a, both versions of uitable are available – the old version is available by adding the ‘v0’ input arg.

Matlab’s uitable exposes only a very limited subset of functionalities and properties to the user. Numerous other functionalities are available by accessing the underlying Java table and hidden Matlab properties. Today I will describe a very common need in GUI tables, that for some unknown reason is missing in Matlab’s uitable: Sorting table data columns.

Last week I explained how we can modify table headers of an ActiveX table control to display sorting icons. In that case, sorting was built-in the control, and the question was just how to display the sorting arrow icon. Unfortunately, Matlab’s uitable does not have sorting built-in, although it’s quite easy to add it, as I shall now show.

Old uitable sorting

The old uitable is the default control used until R2007b, or that can be selected with the ‘v0’ input arg since R2008a. It was based on an internal MathWorks extension of the standard Java Swing JTable – a class called com.mathworks.widgets.spreadsheet.SpreadsheetTable.

Users will normally try to sort columns by clicking the header. This has been a deficiency of JTable for ages. To solve this for the old (pre-R2008a) uitable, download one of several available JTable sorter classes, or my TableSorter class (available here). Add the TableSorter.jar file to your static java classpath (via edit('classpath.txt')) or your dynamic classpath (javaaddpath('TableSorter.jar')).

% Display the uitable and get its underlying Java object handle
[mtable,hcontainer] = uitable('v0', gcf, magic(3), {'A', 'B', 'C'});   % discard the 'v0' in R2007b and earlier
jtable = mtable.getTable;   % or: get(mtable,'table');
 
% We want to use sorter, not data model...
% Unfortunately, UitablePeer expects DefaultTableModel not TableSorter so we need a modified UitablePeer class
% But UitablePeer is a Matlab class, so use a modified TableSorter & attach it to the Model
if ~isempty(which('TableSorter'))
   % Add TableSorter as TableModel listener
   sorter = TableSorter(jtable.getModel());
   jtable.setModel(sorter);
   sorter.setTableHeader(jtable.getTableHeader());
 
   % Set the header tooltip (with sorting instructions)
   jtable.getTableHeader.setToolTipText('<html>&nbsp;<b>Click</b> to sort up; <b>Shift-click</b> to sort down<br />&nbsp;...</html>');
 
else
   % Set the header tooltip (no sorting instructions...)
   jtable.getTableHeader.setToolTipText('<html>&nbsp;<b>Click</b> to select entire column<br />&nbsp;<b>Ctrl-click</b> (or <b>Shift-click</b>) to select multiple columns&nbsp;</html>');
end

Sorted uitable - old version

Sorted uitable - old version

New uitable sorting

The new uitable is based on JIDE’s com.jidesoft.grid.SortableTable and so has built-in sorting support – all you need to do is to turn it on. First get the underlying Java object using my FindJObj utility:

% Display the uitable and get its underlying Java object handle
mtable = uitable(gcf, 'Data',magic(3), 'ColumnName',{'A', 'B', 'C'});
jscrollpane = findjobj(mtable);
jtable = jscrollpane.getViewport.getView;
 
% Now turn the JIDE sorting on
jtable.setSortable(true);		% or: set(jtable,'Sortable','on');
jtable.setAutoResort(true);
jtable.setMultiColumnSortable(true);
jtable.setPreserveSelectionsAfterSorting(true);

Note: the Matlab mtable handle has a hidden Sortable property, but it has no effect – use the Java property mentioned above instead. I assume that the hidden Sortable property was meant to implement the sorting behavior in R2008a, but MathWorks never got around to actually implement it, and so it remains this way to this day.

A more detailed report

I have prepared a 45-page PDF report about using and customizing Matlab’s uitable, which greatly expands on the above. This report is available for $25 here (please allow up to 48 hours for email delivery). The report includes the following (more details here):

  • comparison of the old vs. the new uitable implementations
  • description of the uitable properties and callbacks
  • alternatives to uitable using a variety of technologies
  • updating a specific cell’s value
  • setting background and foreground colors for a cell or column
  • using dedicated cell renderer and editor components
  • HTML processing
  • setting dynamic cell-specific tooltip
  • setting dynamic cell-specific drop-down selection options
  • using a color-selection drop-down for cells
  • customizing scrollbars
  • customizing column widths and resizing
  • customizing selection behavior
  • data sorting (expansion of today’s article)
  • data filtering (similar to Excel’s data filtering control)
  • merging table cells
  • programmatically adding/removing rows
  • numerous links to online resources
  • overview of the JIDE grids package, which contains numerous extremely useful GUI controls and components
]]>
https://undocumentedmatlab.com/blog_old/uitable-sorting/feed 46
Uitab colors, icons and imageshttps://undocumentedmatlab.com/blog_old/uitab-colors-icons-images https://undocumentedmatlab.com/blog_old/uitab-colors-icons-images#comments Wed, 10 Nov 2010 18:00:01 +0000 https://undocumentedmatlab.com/?p=1955 Related posts:
  1. Figure toolbar components Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to access existing toolbar icons and how to add non-button toolbar components....
  2. Customizing uitree nodes – part 1 This article describes how to customize specific nodes of Matlab GUI tree controls created using the undocumented uitree function...
  3. Customizing uitree nodes – part 2 This article shows how Matlab GUI tree nodes can be customized with checkboxes and similar controls...
  4. Uitable sorting Matlab's uitables can be sortable using simple undocumented features...
]]>
A few months ago I published a post about Matlab’s semi-documented tab-panel functionality, where I promised a follow-up article on tab customizations. A reader of this blog asked a related question earlier today, so I decided it’s about time I fulfilled this promise.

As with most Matlab controls, the underlying Java component enables far greater customization than possible using plain Matlab. Today I will show three specific customizations. We start with a basic tab group, and get the underlying Java component:

% Prevent an annoying warning msg
warning off MATLAB:uitabgroup:OldVersion
 
% Prepare a tab-group consisting of two tabs
hTabGroup = uitabgroup; drawnow;
tab1 = uitab(hTabGroup, 'title','Panel 1');
a = axes('parent', tab1); surf(peaks);
tab2 = uitab(hTabGroup, 'title','Panel 2');
uicontrol(tab2, 'String','Close', 'Callback','close(gcbf)');
 
% Get the underlying Java reference (use hidden property)
jTabGroup = getappdata(handle(hTabGroup),'JTabbedPane');

Foreground & background tab colors

We can set the tab font color using setForeground() and setForegroundAt(), or via HTML. Note that setForegroundAt() overrides anything set by setForeground(). Also remember that Java uses 0-based indexing so tab #1 is actually the second tab:

% Equivalent manners to set a red tab foreground:
jTabGroup.setForegroundAt(1,java.awt.Color(1.0,0,0)); % tab #1
jTabGroup.setTitleAt(1,'<html><font color="red"><i>Panel 2');
jTabGroup.setForeground(java.awt.Color.red);

Unfortunately, the corresponding setBackgroundAt(tabIndex,color) method has no visible effect, and the Matlab-extended tabs keep their white/gray backgrounds. A similar attempt to modify the tab’s BackgroundColor property fails, since Matlab made this property unmodifiable (=’none’). A simple solution is to use a CSS background:

% Equivalent manners to set a yellow tab background:
jTabGroup.setTitleAt(0,'<html><div style="background:#ffff00;">Panel 1');
jTabGroup.setTitleAt(0,'<html><div style="background:yellow;">Panel 1');

uitabgroup with non-default forground and background tab colors and fonts

uitabgroup with non-default forground and background tab colors and fonts

We can set the foreground text color using the CSS color directive. Similarly, we can also set a background gradient image for the tabs, using the CSS background-image directive. Which leads us to our next customization:

Icon images

Icons and sub-components can be added to the tabs. Unfortunately, for some reason that I do not fully understand, jTabGroup.setIconAt() has no apparent effect. The solution is to set our own custom control as the requested tab, and add our icon (or other customizations) to it. Here is a simple example:

% Add an icon to tab #1 (=second tab)
icon = javax.swing.ImageIcon('C:\Yair\save.gif');
jLabel = javax.swing.JLabel('Tab #2');
jLabel.setIcon(icon);
jTabGroup.setTabComponentAt(1,jLabel);	% Tab #1 = second tab
 
% Note: icon is automatically grayed when label is disabled
jLabel.setEnabled(false);
jTabGroup.setEnabledAt(1,false);  % disable only tab #1

tab with a custom icon (enabled)
tab with a custom icon (enabled)

tab with a custom icon (enabled & disabled)

Close buttons

Now let’s try a more complex example, of adding a close (‘x’) button to one of the tabs. Generalizing this code snippet is left as an exercise to the reader:

% First let's load the close icon
jarFile = fullfile(matlabroot,'/java/jar/mwt.jar');
iconsFolder = '/com/mathworks/mwt/resources/';
iconURI = ['jar:file:/' jarFile '!' iconsFolder 'closebox.gif'];
icon = javax.swing.ImageIcon(java.net.URL(iconURI));
 
% Now let's prepare the close button: icon, size and callback
jCloseButton = handle(javax.swing.JButton,'CallbackProperties');
jCloseButton.setIcon(icon);
jCloseButton.setPreferredSize(java.awt.Dimension(15,15));
jCloseButton.setMaximumSize(java.awt.Dimension(15,15));
jCloseButton.setSize(java.awt.Dimension(15,15));
set(jCloseButton, 'ActionPerformedCallback',@(h,e)delete(tab2));
 
% Now let's prepare a tab panel with our label and close button
jPanel = javax.swing.JPanel;	% default layout = FlowLayout
set(jPanel.getLayout, 'Hgap',0, 'Vgap',0);  % default gap = 5px
jLabel = javax.swing.JLabel('Tab #2');
jPanel.add(jLabel);
jPanel.add(jCloseButton);
 
% Now attach this tab panel as the tab-group's 2nd component
jTabGroup.setTabComponentAt(1,jPanel);	% Tab #1 = second tab

tab with an attached close button

tab with an attached close button

Next week’s article will conclude the series on Matlab’s uitab. Any particular customization you are interested in? Please do post a comment.

Addendum Oct 3 2014: the uitab and uitabgroup functions have finally become fully supported and documented in Matlab version 8.4 (R2014b). However, the Java-based customizations shown in this article are still unsupported and undocumented, although they remain practically unchanged from what I’ve described in this article, four years earlier.

]]>
https://undocumentedmatlab.com/blog_old/uitab-colors-icons-images/feed 39
Customizing uitree nodes – part 1https://undocumentedmatlab.com/blog_old/customizing-uitree-nodes https://undocumentedmatlab.com/blog_old/customizing-uitree-nodes#comments Wed, 25 Aug 2010 18:00:20 +0000 https://undocumentedmatlab.com/?p=1835 Related posts:
  1. Uitab colors, icons and images Matlab's semi-documented tab panels can be customized using some undocumented hacks...
  2. Figure toolbar components Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to access existing toolbar icons and how to add non-button toolbar components....
  3. Customizing uitree nodes – part 2 This article shows how Matlab GUI tree nodes can be customized with checkboxes and similar controls...
  4. Customizing uitree This article describes how to customize Matlab GUI tree controls created using the undocumented uitree function...
]]>
In my previous posts, I introduced the semi-documented uitree function that enables displaying data in a hierarchical (tree) control in Matlab GUI, and showed how it can be customized. Today, I will continue by describing how specific uitree nodes can be customized.

To start the discussion, let’s re-create last week’s simple uitree:

% Fruits
fruits = uitreenode('v0', 'Fruits', 'Fruits', [], false);
fruits.add(uitreenode('v0', 'Apple',  'Apple',  [], true));
fruits.add(uitreenode('v0', 'Pear',   'Pear',   [], true));
fruits.add(uitreenode('v0', 'Banana', 'Banana', [], true));
fruits.add(uitreenode('v0', 'Orange', 'Orange', [], true));
 
% Vegetables
veggies = uitreenode('v0', 'Veggies', 'Vegetables', [], false);
veggies.add(uitreenode('v0', 'Potato', 'Potato', [], true));
veggies.add(uitreenode('v0', 'Tomato', 'Tomato', [], true));
veggies.add(uitreenode('v0', 'Carrot', 'Carrot', [], true));
 
% Root node
root = uitreenode('v0', 'Food', 'Food', [], false);
root.add(veggies);
root.add(fruits);
 
% Tree
figure('pos',[300,300,150,150]);
mtree = uitree('v0', 'Root', root);

User-created tree    User-created tree

User-created tree

Labels

Node labels (descriptions) can be set using their Name property (the second uitreenode data argument). Note that the horizontal space allotted for displaying the node name will not change until the node is collapsed or expanded. So, if the new name requires more than the existing space, it will be displayed as something like “abc…”, until the node is expanded or collapsed.

Node names share the same HTML support feature as all Java Swing labels. Therefore, we can specify font size/face/color, bold, italic, underline, super-/sub-script etc.:

txt1 = '<html><b><u><i>abra</i></u>';
txt2 = '<font color="red"><sup>kadabra</html>';
node.setName([txt1,txt2]);

HTML-enriched tree nodes

HTML-enriched tree nodes

Icons

Tree-node icons can be specified during node creation, as the third data argument to uitreenode, which accepts an icon-path (a string):

iconPath = fullfile(matlabroot,'/toolbox/matlab/icons/greenarrowicon.gif');
node = uitreenode('v0',value,name,iconPath,isLeaf);

Tree node icons can also be created or modified programmatically in run-time, using Matlab’s im2java function. Icons can also be loaded from existing files as follows (real-life programs should check and possibly update jImage’s size to 16 pixels, before setting the node icon, otherwise the icon might get badly cropped; also note the tree-refreshing action):

jImage = java.awt.Toolkit.getDefaultToolkit.createImage(iconPath);
veggies.setIcon(jImage);
veggies.setIcon(im2java(imread(iconPath)));  % an alternative
 
% refresh the veggies node (and all its children)
mtree.reloadNode(veggies);

Setting node icon

Setting node icon

Behavior

Nodes can be modified from leaf (non-expandable) to parent behavior (=expandable) by setting their LeafNode property (a related property is AllowsChildren):

set(node,'LeafNode',false);  % =expandable
node.setLeafNode(0);  % an alternative

One of the questions I was asked was how to “disable” a specific tree node. One way would be to modify the tree’s ExpandFcn callback. Another way is to use a combination of HTML rendering and the node’s AllowsChildren property:

label = char(veggies.getName);
veggies.setName(['<html><font color="gray">' label]);
veggies.setAllowsChildren(false);
t.reloadNode(veggies);

Disabled node

Disabled node

Another possible behavioral customization is adding a context-menu to a uitree. We can set node-specific tooltips using similar means.

Answering a reader’s request from last week, tree nodes icons can be used to present checkboxes, radio buttons and other similar node-specific controls. This can actually be done in several ways, that will be explored in next week’s article.

There are numerous other possible customizations – if readers are interested, perhaps I will describe some of them in future articles. If you have any special request, please post a comment below.

]]>
https://undocumentedmatlab.com/blog_old/customizing-uitree-nodes/feed 21
Syntax highlighted labels & panelshttps://undocumentedmatlab.com/blog_old/syntax-highlighted-labels-panels https://undocumentedmatlab.com/blog_old/syntax-highlighted-labels-panels#comments Wed, 14 Jul 2010 16:02:26 +0000 https://undocumentedmatlab.com/?p=1738 Related posts:
  1. Uitable sorting Matlab's uitables can be sortable using simple undocumented features...
  2. Uitable customization report Matlab's uitable can be customized in many different ways. A detailed report explains how. ...
  3. FindJObj GUI – display container hierarchy The FindJObj utility can be used to present a GUI that displays a Matlab container's internal Java components, properties and callbacks....
  4. JGraph and BDE This article shows how to display graph-theory diagrams in Matlab using several different Java libraries...
]]>
A few weeks ago, a reader of my article about rich Matlab editbox contents asked whether it is possible to display syntax-highlighted contents, i.e. contents whose color changes based on its underlying text, often called syntax hilite in affection. I gave a very specific answer in a reply comment, which I expand in today’s full-length article.

Matlab has two built-in Java classes that can present syntax-highlighted text: SyntaxTextLabel presents single-line labels, while SyntaxTextPane presents a multi-line editor pane. Both of these classes support C, HTML/XML, Java and Matlab syntax highlighting, as well as standard plaint-text. Some related JIDE classes are also described.

SyntaxTextLabel

SyntaxTextLabel is used to display a syntax-highlighted single-line text label according to the specified programming language: C_STYLE, HTML_STYLE, JAVA_STYLE, PLAIN_STYLE and of course M_STYLE for Matlab code:

str = 'for id=1:3, set(h(id),''string'',num2str(id)); end  % Matlab code';
codeType = com.mathworks.widgets.SyntaxTextLabel.M_STYLE;
jCodeLabel = com.mathworks.widgets.SyntaxTextLabel(str,codeType)
[jhLabel,hContainer] = javacomponent(jCodeLabel,[10,10,300,20],gcf);

SyntaxTextLabels (different code styles)

SyntaxTextLabels (different code styles)

StyledLabel

More flexibility in the displayed label styles can be achieved with HTML/CSS, and the bundled JIDE class com.jidesoft.swing.StyledLabel provides even more flexibility:

import java.awt.*
import com.jidesoft.swing.*
str = 'Mixed Underlined Strikethrough Super and Subscript combo Styles';
com.mathworks.mwswing.MJUtilities.initJIDE;
jStyledLabel = StyledLabel(str); 
styles = [StyleRange(0,5,  Font.BOLD,   Color.BLUE), ...
          StyleRange(6,10, Font.PLAIN,StyleRange.STYLE_UNDERLINED),...
          StyleRange(17,13,Font.PLAIN,  Color.RED,   ...
                           StyleRange.STYLE_STRIKE_THROUGH), ...
          StyleRange(31,5, Font.PLAIN,  Color.BLUE,  ...
                           StyleRange.STYLE_SUPERSCRIPT), ...
          StyleRange(37,3, Font.ITALIC, Color.BLACK), ...
          StyleRange(41,9, Font.PLAIN,  Color.BLUE,  ...
                           StyleRange.STYLE_SUBSCRIPT), ...
          StyleRange(51,5, Font.PLAIN,  StyleRange.STYLE_WAVED + ...
                           StyleRange.STYLE_STRIKE_THROUGH)];
jStyledLabel.setStyleRanges(styles);
[jhLabel,hContainer] = javacomponent(jStyledLabel,[10,10,300,20],gcf);

JIDE StyledLabel (different font styles)

JIDE StyledLabel (different font styles)

StyledLabels have subclasses that can be used to present styled text in tables, trees or lists. JIDE also provides the convenient StyledLabelBuilder, which enables easy multi-style text construction.

Finally, JIDE provides the ClickThroughStyledLabel, a StyledLabel extension that allows setting a target component, so that mouse clicks on the label will actually trigger the target component. This can be useful in forms where components have adjacent descriptive labels.

SyntaxTextPane

Multi-line syntax-highlighted code can be displayed with Matlab’s SyntaxTextPane class. SyntaxTextPane uses MIME types rather than styles for syntax-highlighting, but the end-result appears similar:

jCodePane = com.mathworks.widgets.SyntaxTextPane;
codeType = jCodePane.M_MIME_TYPE;  % ='text/m-MATLAB'
jCodePane.setContentType(codeType)
str = ['% create a file for output\n' ...
       '!touch testFile.txt\n' ...
       'fid = fopen(''testFile.txt'', ''w'');\n' ...
       'for i=1:10\n' ...
       '    % Unterminated string:\n' ...
       '    fprintf(fid,''%6.2f \\n, i);\n' ...
       'end'];
str = sprintf(strrep(str,'%','%%'));
jCodePane.setText(str)
jScrollPane = com.mathworks.mwswing.MJScrollPane(jCodePane);
[jhPanel,hContainer] = javacomponent(jScrollPane,[10,10,300,100],gcf);

SyntaxTextPane panel (Matlab MIME type)

SyntaxTextPane panel (Matlab MIME type)

The nice thing about SyntaxTextPane is that it syntax-highlights on-the-fly as you type or edit in the SyntaxTextPane (assuming you have not disabled editing with the setEditable(flag) method). This is exactly the behavior we have come to expect in the full-blown Matlab editor, and can now be embedded as a simple panel within our GUI.

Despite its misleadingly-simple look, SyntaxTextPane actually has most capabilities of the full-blown editor, not just syntax highlighting. This includes multiple undo/redo actions; smart indentation/commenting; automatic indication of corresponding block elements (if-end, for-end, etc. – also known as delimiter matching); search/replace, drag-and-drop and cut-copy-paste support; and many more.

Interested readers can use the uiinspect and checkClass utilities to explore the full capabilities offered by SyntaxTextPane. In this respect it would be helpful to also look at its super-class (SyntaxTextPaneBase) and the related SyntaxTextPaneUtilities class.

Summary

These Java classes are examples of built-in classes that can be used in Matlab applications, enabling a much richer GUI experience than possible using the standard (documented/supported) Matlab widgets.

As I have shown above, using these classes is extremely easy, and requires absolutely no Java knowledge. On the flip side, these internal Matlab classes may easily break in any future Matlab release, so be extra careful when deciding to use them. Future articles in this website will describe other similarly-useful built-in classes.

Have you found any other useful built-in Matlab class? If so, please post a comment.

]]>
https://undocumentedmatlab.com/blog_old/syntax-highlighted-labels-panels/feed 18