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

Setting system tray icons

March 24, 2009 15 Comments

Java 1.6, included in Matlab releases since Matlab 7.5 (R2007b), enables programmatic access to system tray icons on such systems that support this functionality (Windows, Linux and possibly others).  If the SystemTray object indicates that it isSupported(), then a TrayIcon can be added, along with an associated tooltip and popup menu:

sysTray = java.awt.SystemTray.getSystemTray;
if (sysTray.isSupported)
   myIcon = fullfile(matlabroot,'/toolbox/matlab/icons/matlabicon.gif');
   iconImage = java.awt.Toolkit.getDefaultToolkit.createImage(myIcon);
   trayIcon = java.awt.TrayIcon(iconImage, 'initial tooltip');
   trayIcon.setToolTip('click this icon for applicative context menu');
end

sample system tray icon
sample system tray icon

The icon image can be made to automatically resize to the system-tray dimensions, using the trayIcon.setImageAutoSize(true) method (by default the icon image will maintain its original size, getting cropped or appearing small as the case may be).
Of course, after initial setup, all the sys-tray icon’s properties (icon image, popup, tooltip etc.) can be modified with convenient set methods (setImage(), setPopupMenu(), setTooltip()) or via Matlab’s set() function.
Icon popup menus are very similar in concept to Matlab uicontextmenus. Unfortunately, they need to be programmed separately since Java does not accept uicontextmenu handles. This is actually quite easy, as the following code snippet shows:

% Prepare the context menu
menuItem1 = java.awt.MenuItem('action #1');
menuItem2 = java.awt.MenuItem('action #2');
menuItem3 = java.awt.MenuItem('action #3');
% Set the menu items' callbacks
set(menuItem1,'ActionPerformedCallback',@myFunc1);
set(menuItem2,'ActionPerformedCallback',{@myfunc2,data1,data2});
set(menuItem3,'ActionPerformedCallback','disp(''action #3...'')');
% Disable one of the menu items
menuItem2.setEnabled(0);        % or: set(menuItem2,'Enabled','off');
% Add all menu items to the context menu (with internal separator)
jmenu = java.awt.PopupMenu;
jmenu.add(menuItem1);
jmenu.add(menuItem2);
jmenu.addSeparator;
jmenu.add(menuItem3);
% Finally, attach the context menu to the icon
trayIcon.setPopupMenu(jmenu);    % or: set(trayIcon,'PopupMenu',jmenu);

Tray icon context (right-click) menu
Tray icon context (right-click) menu

Unfortunately, neither the icon tooltip nor its popup menu supports HTML. The reason is that SystemTray is actually not part of Swing at all. The system-tray functionality resides in the java.awt package, and does not inherit javax.swing.JLabel’s (and Matlab uicontrols) support for HTML.
I have created a utility function called SYSTRAY, which is a convenience function that facilitates the setup and update of system tray icons. SYSTRAY (with source code) can be downloaded from the File Exchange.
In a separate post, I shall detail how informational pop-up messages can be attached to system-tray icons. This requires a bit of Java-hacking, so is beyond the scope of a single blog post.
Please note the new TODO page, which details my future posts. I would be happy to hear your requests for new topics, or telling me which topics you’d like to see earlier than others.
Addendum (May 15, 2009): A kind reader today left a comment on another post of this blog with a solution for some reported Java exceptions when using systray in Matlab R2008b onward.

Related posts:

  1. Setting system tray popup messages – System-tray icons and messages can be programmatically set and controlled from within Matlab, using new functionality available since R2007b....
  2. Setting listbox mouse actions – Matlab listbox uicontrol can be modified to detect mouse events for right-click context menus, dynamic tooltips etc....
  3. Uitab colors, icons and images – Matlab's semi-documented tab panels can be customized using some undocumented hacks...
  4. Matlab toolstrip – part 5 (icons) – Icons can be specified in various ways for toolstrip controls and the app window itself. ...
  5. Setting status-bar text – The Matlab desktop and figure windows have a usable statusbar which can only be set using undocumented methods. This post shows how to set the status-bar text....
  6. EditorMacro v2 – setting Command Window key-bindings – The EditorMacro utility was extended to support built-in Matlab Editor and Command-Window actions and key-bindings. This post describes the changes and the implementation details....
Desktop Icons Java
Print Print
« Previous
Next »
15 Responses
  1. Donn Shull March 25, 2009 at 12:01 Reply

    Hi Yair,

    I see in your TODO list that you are planning to cover the schema package. Even though the schema package is undocumented in general there are a lot of examples available in the toolbox directory to give a general sense of how to use it. There is not however a good example of how easy it is to use the schema.class javaInterfaces property to seemlessly access UDD objects from java code. I think people would be interested in that.

    Donn

  2. wei March 31, 2009 at 05:39 Reply

    Hi Yair,
    How does one set icon image, e.g. JButton, for uicomponent you posted?

    Thank you.

    • Yair Altman March 31, 2009 at 08:23 Reply

      @wei – assuming your component has a reference handle (let’s say jButton), follow this example:

      myIcon = fullfile(matlabroot,'/toolbox/matlab/icons/matlabicon.gif');
      iconImage = java.awt.Toolkit.getDefaultToolkit.createImage(myIcon);
      jButton.setIcon(javax.swing.ImageIcon(iconImage));
      

      Swing button icon

      • wei March 31, 2009 at 13:16

        @Yair,
        I bypassed awt and directly went

         iconImage = javax.swing.ImageIcon(myIcon);
         jButton.setIcon(iconImage);
        

        Any difference?

      • Yair Altman March 31, 2009 at 14:15

        @wei – your method is ok for simple filenames – I simply forgot that the ImageIcon constructor also accepts a filename. In practice, within that constructor it calls the awt Toolkit to process the file so there’s no performance difference, but obviously the code is more readable/maintainable this way. BTW, you can also use URL images, for example:

        jarFile = fullfile(matlabroot,'/java/jar/mwt.jar');
        iconsFolder = '/com/mathworks/mwt/resources/';
        myIcon = ['jar:file:/' jarFile '!' iconsFolder 'save.gif'];
        myIcon = java.net.URL(myIcon);  % not necessary for simple external files
        jSave.setIcon(javax.swing.ImageIcon(myIcon));
        

        If you wish to use the icon to set a specific component mouse cursor (hover pointer), you DO need to use the awt.Toolkit:

        myIcon = fullfile(matlabroot,'/toolbox/matlab/icons/matlabicon.gif');
        imageToolkit = java.awt.Toolkit.getDefaultToolkit;
        iconImage = imageToolkit.createImage(myIcon);
        hotSpot = java.awt.Point(20,0);   % =Matlab icon point (top) after 16x16=>32x32 resize
        myCursor = imageToolkit.createCustomCursor(iconImage,hotSpot,'My Cursor');
        jButton.setCursor(myCursor);
        

        custom button cursor

      • wei March 31, 2009 at 15:11

        @Yair, That’s nice to know. Thank you.

  3. wei April 3, 2009 at 08:05 Reply

    @Yair, Can one change figure’s icon wihtout JavaFrame?

    • Yair Altman April 4, 2009 at 09:55 Reply

      wei – you can change the figure icon (not without the JavaFrame), but I’m told this may violate Matlab’s license. I’m really not sure why MathWorks (TMW) chose to limit this pretty harmless customization, but there you have it. In all my posts I try to stay on the good side of the line, so I’m afraid I can’t help you here… If you have a specific need for a customer project, then perhaps if you approach TMW they’ll agree to give you special permission.

  4. Jack Rayman July 19, 2014 at 06:49 Reply

    Hi.

    I’m using your code like this in Matlab r2014a in windows 8.1 First I got a java exception so I used this:

    t=java.awt.Toolkit.getDefaultToolkit();
    ev=t.getAWTEventListeners()
    for i=1:length(ev)
        str=ev(i).getListener().getClass.toString
        if str.indexOf('com.mathworks.mwswing.desk.DTSelectionManager')>=0 || ...
                str.indexOf('javax.swing.plaf.basic.BasicLookAndFeel')>=0
            t.removeAWTEventListener(ev(i))
        end
    end
     
    sysTray = java.awt.SystemTray.getSystemTray;
    if (sysTray.isSupported)
        myIcon = fullfile(matlabroot,'/toolbox/matlab/icons/matlabicon.gif');
        iconImage = java.awt.Toolkit.getDefaultToolkit.createImage(myIcon);
        trayIcon = java.awt.TrayIcon(iconImage, 'initial tooltip');
        trayIcon.setToolTip('click this icon for applicative context menu');
    end

    t=java.awt.Toolkit.getDefaultToolkit(); ev=t.getAWTEventListeners() for i=1:length(ev) str=ev(i).getListener().getClass.toString if str.indexOf('com.mathworks.mwswing.desk.DTSelectionManager')>=0 || ... str.indexOf('javax.swing.plaf.basic.BasicLookAndFeel')>=0 t.removeAWTEventListener(ev(i)) end end sysTray = java.awt.SystemTray.getSystemTray; if (sysTray.isSupported) myIcon = fullfile(matlabroot,'/toolbox/matlab/icons/matlabicon.gif'); iconImage = java.awt.Toolkit.getDefaultToolkit.createImage(myIcon); trayIcon = java.awt.TrayIcon(iconImage, 'initial tooltip'); trayIcon.setToolTip('click this icon for applicative context menu'); end

    After running this code I have a blank icon near clock without no message and without no icon. What should I do?

  5. Ange Laure March 12, 2015 at 09:42 Reply

    Hi Yair,

    did you already get a way to fix the java exceptions in matlab?

    Thanks,
    Ange Laure

    • Yair Altman March 12, 2015 at 09:47 Reply

      @Ange – no, there are many other higher-priority items on my plate…

  6. Ange Laure March 13, 2015 at 10:53 Reply

    Hi Yair,

    thanks! I get another problem. I have implemented a GUI in Java which contains Icon (ImageIcon). Then I exported the class files in a .jar file which I add to the classpath von Matlab. Unfortunately everything on the GUI appear apart from the icons. Do you know what I am doing wrong?

    Regards,
    Ange Laure

    • Yair Altman March 14, 2015 at 09:47 Reply

      Matlab is obviously not finding your icon in the stated classpath…
      If you need assistance debugging your specific program, contact me by email for a short consultancy.

  7. Sam Roberts March 16, 2016 at 11:54 Reply

    Hi Yair,

    You recommend calling systray = java.awt.SystemTray.getSystemTray, and then systray.isSupported afterwards to check if the system tray is supported. Unfortunately, if the system tray isn’t supported (for example, I just tried this when running MATLAB remotely over an X Window), the original call to getSystemTray can error.

    Instead, you can call java.awt.SystemTray.isSupported. This returns true or false, and doesn’t error in an unsupported environment. Call getSystemTray only if that returns true.

    • Yair Altman March 16, 2016 at 12:36 Reply

      thanks for the update Sam

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