Undocumented Matlab
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT

Aligning uicontrol contents

September 22, 2016 8 Comments

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!'});

% 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';

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

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'});

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.

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. Additional uicontrol tooltip hacks – Matlab's uicontrol tooltips have several limitations that can be overcome using the control's underlying Java object....
  4. Setting line position in an edit-box uicontrol – Matlab uicontrols have many useful features that are only available via Java. Here's how to access them....
  5. uicontrol side-effect: removing figure toolbar – Matlab's built-in uicontrol function has a side-effect of removing the figure toolbar. This was undocumented until lately. This article describes the side-effect behavior and how to fix it....
  6. Rich Matlab editbox contents – The Matlab editbox uicontrol does not handle HTML contents as do other uicontrols. In this article I show how this limitation can be removed....
GUI HTML Pure Matlab uicontrol Undocumented feature
Print Print
« Previous
Next »
8 Responses
  1. Les Beckham August 12, 2017 at 06:01 Reply

    Interesting post, as always.

    I’m curious why you state that “HTML formatting is generally frowned-upon compared to the alternatives”. By whom? And why?

    Perhaps you can elaborate.

    Thank you

    • Yair Altman August 12, 2017 at 20:37 Reply

      @Les – HTML formatting is more CPU and memory-intensive, while being less powerful, than using Cell Renderers (details). Also, whenever you update an HTML-formatted cell, you’d see the full HTML string as the text in the cell content, which is a bit awkward. Also, if you try to get the values in the table, you’d need to parse out the HTML tags.

      However, there is no dispute that HTML formatting is super-easy to use, and in many cases the drawbacks listed above pale in comparison to the simplicity and usefulness of HTML formatting. So in general I use HTML formatting for most simple formatting, and I only use Cell Renderers for large tables (with numerous formatted cells), when the formatting is not easy to achieve with HTML, and/or when the table cells need to be updated by the user.

  2. Narendra Kintali September 20, 2017 at 19:12 Reply

    Hi sir, I am using uitable for my project, When I am trying to display a array of values. The values are aligned to top, which makes them not visible. So I need to change the height of row in uitable, Please tell me How can I change Height of row in uitable.

    • Yair Altman September 24, 2017 at 10:39 Reply

      @Narendra – you can use the underlying Java table’s setRowHeight() method

      hTable = uitable(...);
      jTable = findjobj(hTable);
      try jTable = jTable.getViewport.getView; catch, end
       
      jTable.setRowHeight(10);    % all rows = 10px
      jTable.setRowHeight(5,12);  % row #6 = 12px

      hTable = uitable(...); jTable = findjobj(hTable); try jTable = jTable.getViewport.getView; catch, end jTable.setRowHeight(10); % all rows = 10px jTable.setRowHeight(5,12); % row #6 = 12px

      • Narendra Kintali September 29, 2017 at 01:36

        sir,

        Its not working. It gives error as “No appropriate method, property, or field ‘setRowHeight’ for class ‘matlab.ui.control.Table’.”

      • Yair Altman September 29, 2017 at 09:19

        These customizations do not work with web-based figures (created with App Designer) – only with tables that are created in non-web figures, using GUIDE or the uitable function.

  3. Ajay Krishna March 23, 2021 at 05:17 Reply

    Hello Yair,

    i tried replicating the example with all the cells center aligned.
    The problem is when i click the 1st cell the text of neighbouring cell changes to white or it disappears.
    What can be the possible fix for this.
    Please help me out.

    uitable('Units','norm','Pos',[0,0,0.8,0.3],'Data',{'Center','Center','Right'})

    uitable('Units','norm','Pos',[0,0,0.8,0.3],'Data',{'Center','Center','Right'})

    Thanks,
    V. Ajay Krihsna

    • Yair Altman March 23, 2021 at 09:19 Reply

      I assume that you refer to the html tags example for uitable at the bottom of the article. If you click a uitable cell, you enter editor mode, and this may behave in an unexpected manner with html tags.
      To fix this you need to change the uitable column alignment instead of using html tags. This is a bit more difficult to do, but it solves the problem of cell-editing. For information on how to do this, refer to my Matlab-Java programming book, or my uitable customization report.

Leave a Reply
HTML tags such as <b> or <i> are accepted.
Wrap code fragments inside <pre lang="matlab"> tags, like this:
<pre lang="matlab">
a = magic(3);
disp(sum(a))
</pre>
I reserve the right to edit/delete comments (read the site policies).
Not all comments will be answered. You can always email me (altmany at gmail) for private consulting.

Click here to cancel reply.

Useful links
  •  Email Yair Altman
  •  Subscribe to new posts (feed)
  •  Subscribe to new posts (reader)
  •  Subscribe to comments (feed)
 
Accelerating MATLAB Performance book
Recent Posts

Speeding-up builtin Matlab functions – part 3

Improving graphics interactivity

Interesting Matlab puzzle – analysis

Interesting Matlab puzzle

Undocumented plot marker types

Matlab toolstrip – part 9 (popup figures)

Matlab toolstrip – part 8 (galleries)

Matlab toolstrip – part 7 (selection controls)

Matlab toolstrip – part 6 (complex controls)

Matlab toolstrip – part 5 (icons)

Matlab toolstrip – part 4 (control customization)

Reverting axes controls in figure toolbar

Matlab toolstrip – part 3 (basic customization)

Matlab toolstrip – part 2 (ToolGroup App)

Matlab toolstrip – part 1

Categories
  • Desktop (45)
  • Figure window (59)
  • Guest bloggers (65)
  • GUI (165)
  • Handle graphics (84)
  • Hidden property (42)
  • Icons (15)
  • Java (174)
  • Listeners (22)
  • Memory (16)
  • Mex (13)
  • Presumed future risk (394)
    • High risk of breaking in future versions (100)
    • Low risk of breaking in future versions (160)
    • Medium risk of breaking in future versions (136)
  • Public presentation (6)
  • Semi-documented feature (10)
  • Semi-documented function (35)
  • Stock Matlab function (140)
  • Toolbox (10)
  • UI controls (52)
  • Uncategorized (13)
  • Undocumented feature (217)
  • Undocumented function (37)
Tags
AppDesigner (9) Callbacks (31) Compiler (10) Desktop (38) Donn Shull (10) Editor (8) Figure (19) FindJObj (27) GUI (141) GUIDE (8) Handle graphics (78) HG2 (34) Hidden property (51) HTML (26) Icons (9) Internal component (39) Java (178) JavaFrame (20) JIDE (19) JMI (8) Listener (17) Malcolm Lidierth (8) MCOS (11) Memory (13) Menubar (9) Mex (14) Optical illusion (11) Performance (78) Profiler (9) Pure Matlab (187) schema (7) schema.class (8) schema.prop (18) Semi-documented feature (6) Semi-documented function (33) Toolbar (14) Toolstrip (13) uicontrol (37) uifigure (8) UIInspect (12) uitable (6) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
Contact us
Captcha image for Custom Contact Forms plugin. You must type the numbers shown in the image
Undocumented Matlab © 2009 - Yair Altman
This website and Octahedron Ltd. are not affiliated with The MathWorks Inc.; MATLAB® is a registered trademark of The MathWorks Inc.
Scroll to top