HTML support in Matlab uicomponents

A common feature of Java Swing components is their acceptance of HTML (and CSS) for any of their JLabels. Since all Matlab uicontrols are based on Swing-derived components (an undocumented aspect), this Swing feature automatically applies to Matlab uicontrol as well. Whatever can be formatted in HTML (font, color, size, …) is inherently available in Matlab controls. Note that HTML tags do not need to be closed (<tag>…</tag>), although it is good practice to close them properly.

For example, let us create a multi-colored Matlab listbox:

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

Listbox with HTML'ed items

Listbox with HTML colored items

Menus and tooltips can also be customized in a similar fashion:

uicontrol('Style','popup', 'Position',[10,10,150,100], 'String', ...
{'<HTML><BODY bgcolor="green">green background</BODY></HTML>', ...
 '<HTML><FONT color="red" size="+2">Large red font</FONT></HTML>', ...
 '<HTML><BODY bgcolor="#FF00FF"><PRE>fixed-width font'});

Drop-down (popup uicontrol) with HTML'ed items

Drop-down (popup uicontrol) with HTML'ed items

Multi-line HTML'ed tooltip

Multi-line HTML'ed tooltip

Figure main menu modified with HTML items

Figure main menu modified with HTML items

Related posts:

  1. GUI integrated HTML panel Simple HTML can be presented in a Java component integrated in Matlab GUI, without requiring the heavy browser control....
  2. Matlab DDE support Windows DDE is an unsupported and undocumented feature of Matlab, that can be used to improve the work-flow in the Windows environment...
  3. 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...
  4. Spicing up Matlab uicontrol tooltips Matlab uicontrol tooltips can be spiced-up using HTML and CSS, including fonts, colors, tables and images...
  5. 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....
  6. Adding a context-menu to a uitree uitree is an undocumented Matlab function, which does not easily enable setting a context-menu. Here's how to do it....

Categories: GUI, Low risk of breaking in future versions, UI controls

Tags: , ,

Bookmark and SharePrint Print

29 Responses to HTML support in Matlab uicomponents

  1. Ashish Sadanandan says:

    Thanks for starting this blog Yair. It’s fun, and often necessary, to mess with Java directly when doing GUI programming in Matlab and this blog should help a lot with that.

    About displaying HTML in uicontrols, is there a way to do that with static text? Simply changing the style parameter to text in your examples does not work.

    Regards,
    Ashish.

    • This is a good point, Ashish – text uicontrols use a class (com.mathworks.hg.peer.LabelPeer$1 which extends com.mathworks.hg.peer.utils.MultilineLabel) that de-HTMLs the content string for some reason that I do not understanding.

      Instead of using uicontrol(‘style’,'text’,…) you could use javacomponent(‘javax.swing.JLabel’), which uses a standard HTML-compliant label (the string is controlled via its ‘Text’ property).

      Yair

    • Ashish Sadanandan says:

      Perfect! That works, but I ended up using a JButton instead because I could define an ActionPerformedCallback for it, the only way I could figure out to respond to user clicks on a JLabel was to add a mouse listener and I had no idea how to do that on the Matlab side. This is the code I’m using:

      hText = javacomponent( ‘javax.swing.JButton’ );
      set( hText, ‘text’, ‘Select Variable‘ );
      set( hText, ‘BorderPainted’, false );
      set( hText, ‘ContentAreaFilled’, false );
      set( hText, ‘FocusPainted’, false );
      set( hText, ‘Opaque’, true );
      set( hText, ‘ActionPerformedCallback’, @myCallback );

      Now, the next question is, is there a way to make it behave like a HyperLink on hovering i.e. change the cursor to the hand icon, like it does in a web browser?

    • Ah, Ashish – this one’s easy: to change the cursor to a hand icon, simply do this:

      hText.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.HAND_CURSOR));

      Note that in order to prevent memory leaks, it is advisable to use the jObject.setProperty() or set(handle(jObject),’Property’,…) formats, instead of set(jObject,’Property’,…).

      Yair

    • Ashish Sadanandan says:

      Thanks for the tip about using the SET function, I was digging around a little bit more about that and came up with this link:
      http://mathforum.org/kb/message.jspa?messageID=5950839&tstart=0

      Is what he says about explicitly setting java handles to [] true? I’m not doing that at the moment, but I could stuff all the java handles into GUIDATA and set them to empty in the DeleteFcn callback for the figure containing the Java components.

      Thanks again for answering all my questions, pretty soon you’ll be able to create a new blog post from just these questions :-)

      Oh and I have some feedback about the website, it’s minor and nothing that a text editor can’t fix in a few seconds, but the code that you post cannot be copy-pasted into the Matlab command line directly because of the ‘, “, … etc. characters which instead of the ASCII versions are some HTML versions. The … for instance is a single character instead of 3 .s

  2. Ashish Sadanandan says:

    Forgot to ask one more question I had. I create the JButton using javacomponent and then call the handle function before setting the ActionPerformedCallback

    hText = javacomponent( ‘javax.swing.JButton’, pos, hPanel );
    hText.setText( ‘MyButton’ );
    hText = handle( hText, ‘CallbackProperties’ );
    set( hText, ‘ActionPerformedCallback’, @VarSelectCallback );

    It seems I can move the line containing the call to the HANDLE function right after creating the JButton and then call all the methods the same way as using the handle returned by javacomponent. Is this true? Are the 2 handles equivalent (other than the fact that you should use the one returned by the HANDLE call to set the callback)?

    • Deleting the java handles (or explicitly setting to []) is really important only for very heavy components (JTable/JTree with lots of data etc.) or for components that keep getting replaced with new instances for programmatic reasons. Otherwise it’s just not worth your programming time…

      Thanks for the feedback about the code snippets font – I fixed it and you can now copy-paste directly into Matlab.

      Your observation about handle() is correct. handle() is a large undocumented topic in Matlab which is on my TODO list. Basically, the handle() object is a Matlab wrapper for the Java reference, and whatever you can do with the Java ref you can do with the handle, with some differences that I’ll detail separately (probably over several posts since the topic is large).

  3. Dani says:

    Can this be used to right align text (or center) in uicontrols? On windows the HorizontalAlignment property only works for text and edit boxes. However, I could not find a html instruction that would do it (p align=right…)

    • Yair Altman says:

      @Dani – the “normal” way to do this is to use HorizontalAlignment. In theory, you could use the style=”text-align:right;” CSS directive. However, it appears that the Java engine does not honor this CSS directive (although it does honor font size/color etc.). it doesn’t hurt to try, just don’t be surprised if it is ignored.

  4. Pingback: Changing Matlab’s Command Window colors - part 2 | Undocumented Matlab

  5. Pingback: Spicing up Matlab uicontrol tooltips | Undocumented Matlab

  6. Jason McMains says:

    Yair, I was messing around with the JLabel HTML, and I have a few different links within it. Is there a way to allow for following these links?

    • Yair Altman says:

      @Jason – you can indeed follow hyperlinks. For a few examples, take a look at my UIINSPECT utility on the File Exchange. Specifically, see the link at the very bottom of the figure window, and also the links within the methods pane on the top-left.

    • Jason McMains says:

      Yair, Thanks for the suggestion. Because I have multiple links, I ended up using a browser instance and inserting the html like this:

      jBrowserPanel=com.mathworks.mlwidgets.html.HTMLBrowserPanel;
      browser = javacomponent(jBrowserPanel,browser_position,gcf);
      html = browser.HTMLRenderer;
      html.setHtmlText(message);
  7. Jason McMains says:

    Just to show another usage of this topic, I’m using it as a font name chooser:

    c=listfonts;
    c=cellfun(@(c) ['<html><Font face="' c '">' c '</font></html>'],c,'uni',false);
    set(findobj('tag','FontName'),'string',c,'value',1)
  8. Pingback: Customizing Matlab labels | Undocumented Matlab

  9. Prasath says:

    An example for Jbutton usage in MATLAB

    function test_javaButton
    import javax.swing.JButton;
    hfig = figure();
    button = JButton('Close');
    [hcomponent, hcontainer] = javacomponent(button, [], hfig);
    set(hcontainer,'units','normalized','position',[.1 .1 .5 .5])
    set(button,'ActionPerformedCallback',@buttonClosePressed);
    return;
     
    function buttonClosePressed(handle,event)
    %doSomething();
    disp('test');
    return;
  10. cintix says:

    Hi,
    Is it possible to assign the color of one plot to what is written inside the listbox?I explain my application: I have an axes and a listbox, when I plot different lines, in the listbox it is shown Plot1,Plot2… and I would like those strings to have the color of its corresponding plotted line…is it possible? I just cant get it…
    Thanks in advance

    • @cintix – yes it is possible. You just need to remember how HTML colors are specified. Here is a very simple example that you can modify for your own needs:

      % Let's modify Plot3 for example:
      color = get(hLine(3),'color');  % => [123,234,45]
      colorStr = sprintf('%d,',int16(color));  % extra ',' is ok
      listStrings{3} = ['<html><font color="rgb(' colorStr ')">Plot3</font></html>'];
      set(hListbox,'string',listStrings);

      Yair

  11. Pingback: Tabbed panes – uitab and relatives | Undocumented Matlab

  12. Fil says:

    Dear all,

    Was just wondering if using this technique I would be able to make some options in a popupmenu change colour and more importantly unselectable?

    Thanks for your invaluable help with this website.

    Fil.

    • @Fil – You can use HTML to define separate item colors (see the example in the main article above), but you can’t define unselectable items.

    • Fil says:

      Thanks Yair,

      So there is no way to create a popupmenu with unselectable options using Matlab or Java?

      Thanks for your help,
      Fil

    • You can use HTML to set popup menu items to gray-italic, but you can’t prevent the user from clicking these items. In your callback, simply ignore any clicks made on your “uselectable” items.

  13. Pingback: Customizing uitree nodes – part 1 | Undocumented Matlab

  14. Aurélien says:

    Hi Yair,

    Just a note about using HTML within uicontrols:

    I use a lot of HTML code for my uicontrols . The only drawback I have found is when you decide to set enable off one of them. For example :

    f = uimenu('Label','Workspace');
    h_ui = uimenu(f,'Label','New Figure','enable','off');

    As the ForegroundColor of “New Figure” label is still in red it is not clear that the label is disabled. I would expect to see the label in grey.

    Currently I remove HTML tags as follows:

    set(rr,'Label',regexprep(get(rr,'Label'),' ]*>', ''),'enable','off')

    Note: The regular expression does not display correctly on your site, I am using this one from this tech-note:
    How can I read an HTML file into MATLAB and discard the HTML tags?

    Except this drawback , using HTML in uicontrols is easy and makes GUIs to be more pretty.

    Aurélien

  15. LL says:

    Hi,
    How to pass a variable in the element?
    var
    for example: I have
    var = 10;

  16. Pingback: Uitable cell colors | Undocumented Matlab

Leave a Reply

Your email address will not be published. Required fields are marked *

*

<pre lang="matlab">
a = magic(3);
sum(a)
</pre>