Archive for May, 2009

Spicing up Matlab uicontrol tooltips

Wednesday, May 27th, 2009

Outside the official Matlab blogs, perhaps the most widely known Matlab-related active blog is BlinkDagger. This blog is certainly worth following, especially for novice Matlab users who could gain fresh angles on regular programming tasks that have a simple solution in Matlab.

In one of their latest posts, BlinkDagger described how to use tooltips in Matlab GUI. In one of this blog’s very first posts, I described how HTML can easily be used with Matlab uicontrols. Let’s now combine these ideas to show how HTML support can easily be used to spice-up the tooltips.

Let’s start with a simple styled multi-line tooltip:

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

Multi-line HTML'ed tooltip

Multi-line HTML'ed tooltip

This technique was used to display the informative tooltip for my Java-based data table utility on the Matlab file Exchange:

Multi-line HTML-styled tooltip

Multi-line HTML-styled tooltip

Tooltips can also be used to present images, using the HTML <img> tag. However, the image src (filename) needs to be formatted in a URL-compliant format such as ‘http://undocumentedmatlab.com/images/table.png‘ or ‘file:/C:\Yair\Undocumented Matlab\Images\table.png’.

If you try to use a non-URL-format filename, the image will not be displayed. Instead, a placeholder box will appear. For example, let’s take the table screenshot above and try to place its filename directly in the tooltip HTML:

filePath = 'C:\Yair\Undocumented Matlab\Images\table.png';
str = ['<html><center><img src="' filePath '"><br>' filePath];
set(hButton,'tooltipString',str);

Tooltip with invalid HTML img source URL

Tooltip with invalid HTML img source URL

If we fix filePath to be a valid URL, it now looks as intended:

filePath = 'C:\Yair\Undocumented Matlab\Images\table.png';
filePath = strrep(['file:/' filePath],'\','/');
str = ['<html><center><img src="' filePath '"><br>' ...
       '<b><font color="blue">' filePath];
set(hButton,'tooltipString',str);

Tooltip with HTML image and caption


Tooltip with HTML image and caption

Note that the tooltip looks enormous (it’s actually even downsized to fit this post…). This is because our HTML <img> was not limited in size and so the tooltip was created to display the screenshot in its original large size. In order to limit the tooltip size, simply add the height and width attributes to the HTML <img> tag, remembering to preserve the original image aspect ratio.

Now that we know the basics, we can really go wild with HTML and CSS formatting. Have you configured any kick-butt tooltip in your application? If so, please share it here.

tic / toc – undocumented option

Friday, May 22nd, 2009

I have recently discussed undocumented features in Matlab’s built-in profiler. Another tool often used for ad-hoc performance profiling of Matlab code are the built-in duo functions tic and toc:

>> tic; magic(500); toc
Elapsed time is 0.474647 seconds.

Both tic and toc are documented functions, but they contain an undocumented option (at least until R2008b – see history below) that enables nested clocking. The problem that is solved using this undocumented option is that if we try to use tic/toc in external function parentFcn and also in the internal function childFcn, we get unexpected results. This happens because our childFcn’s invocation of tic has reset the clock and so parentFcn’s clock is now obviously incorrect:

function parentFcn
 
    % Start clocking
    tic;
 
    % Do something long...
    m1 = magic(1500);
 
    % Call nested function
    toc1 = childFcn;
 
    % Present clock timing
    toc2 = toc;
    fprintf('Elapsed time for childFcn:  %0.3f secs\n',toc1)
    fprintf('Elapsed time for parentFcn: %0.3f secs\n',toc2)
 
 
    % Nested function with separate clocking
    function t = childFcn
        tic;
        m = magic(800);
        t = toc;
    end  % childFcn
 
end  % parentFcn
>> parentFcn
Elapsed time for childFcn:  1.063 secs
Elapsed time for parentFcn: 1.068 secs

The solution: use a separate handle for each clock. The format is very simple:

>> t = tic;
>> toc(t)

This format ensures independent clocking of the clocks. Clockings can now be safely nested and even partial overlap is possible:

function parentFcn
 
    % Start clocking
    t1 = tic;
 
    % Do something long...
    m1 = magic(1500);
 
    % Call nested function
    toc1 = childFcn;
 
    % Present clock timing
    toc2 = toc(t1);
    fprintf('Elapsed time for childFcn:  %0.3f secs\n',toc1)
    fprintf('Elapsed time for parentFcn: %0.3f secs\n',toc2)
 
 
    % Nested function with separate clocking
    function t = childFcn
        tic;
        m = magic(800);
        t = toc;
    end  % childFcn
 
end  % parentFcn
>> parentFcn
Elapsed time for childFcn:  1.123 secs
Elapsed time for parentFcn: 4.992 secs

For the record, this undocumented option was first presented by the MathWorks support team as an official workaround for the aforementioned problem. The solution was originally posted for Matlab R2006b, but actually the option was supported by Matlab versions at least as early as R14SP3 (7.1) – perhaps even earlier (I don’t have ready access to earlier versions). I do know that it was not supported on release R12 aka 6.0, but I don’t know whether it was introduced in 6.5, 7.0 or 7.1. This option has only been documented since R2008b, although it has existed in many earlier releases.

Now here’s a puzzle for all you undoc fans out there: toc has a really undocumented option of using an uninitialized uint64 value, rather than an actual tic handle. It seems that whichever value is passed will always result in the same result, but this result is uncorrelated to any possible event (start of Matlab, midnight etc.). It even works without any prior tic invocation! I would love to hear your thoughts on what you think this strange toc result might represent:

>> toc(uint64(1))
Elapsed time is 72825.947547 seconds.
>> toc(uint64(1234))
Elapsed time is 72826.538296 seconds.

cprintf – display formatted color text in the Command Window

Wednesday, May 13th, 2009

In earlier posts I showed how to modify the Command Window (CW) text and background color, and a very limited method of displaying red (error) and blue (hyperlinked) CW messages. Since then, I was obsessed with finding a better way to CW display text in any color. After lots of trial-and-errors, frustrations and blind alleys – many more than I imagined when I started out – I am now very proud to say that I have solved the problem. My cprintf utility is now available in the File Exchange.

Before I describe the internal implementation, let me show the end result:

cprintf - display styled formatted text in the Command Window

cprintf - display styled formatted text in the Command Window

cprintf relies on ideas presented in the previous two posts mentioned above. Since the CW is a JTextArea which does not enable style segments, I was curious to understand how Matlab is able to display syntax highlighting in it. This is probably done using a dedicated UI class (com.mathworks.mde.cmdwin.CmdWinSyntaxUI), as suggested in the second post. This is an internal Matlab Java class, so we cannot modify it. It seemed like a dead end for a while.

But what if we could fool the UI class to think that our text should be syntax highlighted? at least then we’d have a few more colors to play with (comments=green, strings=purple etc.). So I took a look at the CW’s Document component (that holds all text and style info) and there I saw that Matlab uses several custom attributes with the style and hyperlink information:

  • the SyntaxTokens attribute holds style color strings like ‘Colors_M_Strings’ for strings or ‘CWLink’ for hyperlinks
  • the LinkStartTokens attribute holds the segment start offsets for hyperlinks (-1 for non-hyperlinked, 0+ for hyperlink)
  • the HtmlLink attribute holds the URL target (java.lang.String object) for hyperlinks, or null ([]) for non-hyperlink.

I played a hunch and modified the style of a specific text segment and lo-and-behold, its CW color changed! Unfortunately, I found out that I can’t just fprintf(text) and then modify its style – for some unknown reason Matlab first needs to place the relevant segment in a “styled” mode (or something like this). I tried to fprintf(2,text) to set the red (error) style, but this did not help. But when I prepended a simple hyperlink space character I got what I wanted – I could now modify the subsequent text to any of the predefined syntax highlighting colors/styles.

But is it possible to use any user-defined colors, not just the predefined syntax highlighting colors? I then remembered my reported finding from the first post about CW colors that ‘Colors_M_Strings’ and friends are simply preference color objects that can be set using code like:

>> import com.mathworks.services.*;
>> Prefs.setColorPref('Colors_M_Strings',java.awt.Color(...));

So I played another hunch and tried to set a new custom preference:

>> Prefs.setColorPref('yair',java.awt.Color.green);
>> Prefs.getColorPref('yair')
ans =
java.awt.Color[r=0,g=255,b=0]

So far so good. I now played the hunch and changed the CW text element’s style name from ‘Colors_M_Strings’ to ‘yair’ and luckily the new green color took effect!

So we can now set any style color (and underline it by enclosing the text in a non-target-url hyperlink), as long as we define a style name for it using Prefs.setColorPref. How can we ensure the color uniqueness for multiple colors? The answer was to simply use the integer RGB values of the requested color, something like ‘[47,0,255]‘.

But we still have the hyperlinked (underlined) space before our text – how do we get rid of it? I tried to set the relevant LinkStartTokens entry to -1 but could not: unlike SyntaxTokens which are modifiable Java objects, LinkStartTokens is an immutable numeric vector. I could however set its URL target to null ([]) to prevent the mouse cursor to change when hovering over the space character, but cannot remove the underline. I then had an idea to simply hide the underline by setting the character style to the CW’s background color. The hard part was to come up with this idea – implementation was then relatively easy:

% Get a handle to the Command Window component
mde = com.mathworks.mde.desk.MLDesktop.getInstance;
cw = mde.getClient('Command Window');
xCmdWndView = cw.getComponent(0).getViewport.getComponent(0);

% Store the CW background color as a special color pref
% This way, if the CW bg color changes (via File/Preferences),
% it will also affect existing rendered strs
cwBgColor = xCmdWndView.getBackground;
com.mathworks.services.Prefs.setColorPref('CW_BG_Color',cwBgColor);

% Now update the space character's style to 'CW_BG_Color'
% See within the code: setElementStyle(docElement,'CW_BG_Color',...)

Having thus completed the bulk of the hard detective/inductive work, I now had to contend with several other obstacles before the code could be released to the public:

  • Older Matlab versions (e.g., 7.1 R14) uses the Document style elements slightly differently and I needed to find a solution that will work well on all Matlab 7 versions (this took quite some time…)
  • If the text is not newline (‘\n’)-terminated, sometimes it is not rendered properly. Adding a forced CW repaint() invocation helped solve much of this problem, but some quirks still remain (see cprintf’s help section)
  • Multi-line text (‘abra \n kadbra’) creates several style elements which needed to be processed separately
  • Debugging the code was very difficult because whenever the debugger stopped at a breakpoint, ‘k>>’ is written to the CW thereby ruining the displayed element! I had to devise non-trivial instrumentation and post-processing (see within the code).
  • Taking care of exception handling, argument processing etc. to ensure foolproof behavior. For example, accepting case-insensitive and partial (unique) style names.

Bottom line: we now have a very simple and intuitive utility that is deceivingly simple, but took a few dozen hours of investigation to develop. I never imagined it would be so difficult when I started, but this just makes the engineering satisfaction greater :-)

Any sufficiently advanced technology is indistinguishable from magic – Arthur C. Clarke

As usual, your comments and feedback are most welcome

Addendum (May 15, 2009): CPRINTF was today chosen as the Matlab Central File Exchange Pick of the Week. That was fast! – thanks Brett :-)

Addendum (May 18, 2009): CPRINTF was today removed from the Pick of the Week list, after internal MathWorks discussions that came to a conclusion that by posting CPRINTF on an official Matlab blog it might appear as an official endorsement of undocumented features. I can certainly understand this, so no hard feelings…

cellfun – undocumented performance boost

Monday, May 11th, 2009

Matlab’s built-in cellfun function has traditionally enabled several named (string) processing functions such as ‘isempty’. The relevant code would look like this:

data = cellfun('isempty',cellArray);

In recent years, newer Matlab releases has added support for function handles, so the previous code snippet can now be written as follows:

data = cellfun(@isempty,cellArray);

The newer function-handle format is “cleaner” and more extensive than the former format, accepting any function, not just the limited list of pre-specified processing function names (‘isreal’, ‘islogical’, ‘length’, ‘ndims’, ‘prodofsize’). Some have even reported that the older format has limitations vis-a-vis compilation etc.

All this is well known and documented. However, it turns out that, counter-intuitively (and undocumented), the older format is actually much faster than the newer format for those pre-specified processing function names. The reason appears to be that ‘isempty’ (as well as the other predefined string functions) uses specific code-branches optimized for performance:

>> c = mat2cell(1:1e6,1,repmat(1,1,1e6));
>> tic, d=cellfun('isempty',c); toc
Elapsed time is 0.115583 seconds.
>> tic, d=cellfun(@isempty,c); toc
Elapsed time is 7.493989 seconds.

Perhaps a future Matlab release will improve cellfun’s internal code, to check for function-handle equality to the optimized functions, and use the optimized code branch if possible. When I posted this issue today as a correction to a reader’s misconception, Matlab’s Loren Shure commented as follows:

We could improve cellfun to check function handles to see if they match specified strings. Even then MATLAB would have to be careful in case the user has overridden the built-in version of whatever the string points to.

While this comment seems to imply that the performance boost feature will be maintained and possibly improved in future releases, users should note that this is not guarantied. One could even argue that future code optimizations would be applied to the new (function-handle) format rather than the old string format. The performance pendulum might also change based on user platform. Therefore, users for whom performance is critical should always test both versions on their target system: ‘isempty’ vs. @isempty etc. (note that the corresponding function for ‘prodofsize’ is @numel).

Changing Matlab’s Command Window colors – part 2

Saturday, May 9th, 2009

Following my post on Changing Matlab’s Command Window colors, I received an email asking whether it was possible to temporarily set the Command-Window (CW)’s text color, so that subsequent disp or fprintf commands will be displayed in some specific text color.

The short and simple answer is no: You can change the text color as described in that post, but once you modify it, the entire CW text will be modified accordingly.

Unfortunately, CW (like Swing’s standard JTextArea of which CW is an instance) does not automatically support HTML formatting as most other uicontrols. In fact, CW’s default Document object, which holds all the text-area’s text and font style information, is an extension of Swing’s javax.swing.text.PlainDocument, which does not allow any text style formatting. And the CW object itself is a simple JTextArea, which does not enable using a styled Document object. Perhaps in a future version MathWorks would be willing to use the almost identical (syntactically-wise) JTextPane, which does enable styled text runs.

To a very limited degree, you can use the fact that hyperlinks and error messages have separate styles than standard text (respectively, blue underlined and red). So, you can output text in these styles as follows:

% Use hyperlink style:
>> disp('<a href="">my text</a>')
my text

% Use STDERR (fid=2) style:
>> fprintf(2,'my text\n')
my text

Note: you could possibly get a handle to the JTextArea (see the previous post) and then set its UI property to your tailor-made Java UI class. In this class you can set text segment properties based on whichever properties you wish. This is apparently how Matlab overcame JTextPane’s limitations: they implemented a custom com.mathworks.mde.cmdwin.CmdWinSyntaxUI class that extends javax.swing.plaf.basic.BasicTextAreaUI. But implementing such a custom UI class while retaining Matlab’s syntax-highlighting functionality is most probably very difficult and not worth the effort. So we’ll just wait for some supported method in a future Matlab release.

Addendum (May 13, 2009): I have found a way to enable display of text in any color, as well as underline, in the Command Window. See my post on cprintf for details.

Displaying hidden handle properties

Tuesday, May 5th, 2009

Matlab Handle Graphics (HG) is a great way to manipulate GUI objects. HG handles often have some undocumented hidden properties. One pretty well-known example is the JavaFrame property of the figure handle, which enables access to the GUI’s underlying Java peer object. We can use hidden properties just like any other handle property, using the built-in get and set functions.

But how can we know about these properties? Here are two methods to do so. Like the hidden properties, these two methods are themselves undocumented…

1. use the desktop’s hidden HideUndocumented property:

set(0,'HideUndocumented','off');

From now on, when displaying handle properties using get and set you’ll see the hidden properties.

Note that some of the properties might display a warning indication:

>> get(gcf)
	Alphamap = [ (1 by 64) double array]
	BackingStore = on
	CloseRequestFcn = closereq
	Color = [0.8 0.8 0.8]
	Colormap = [ (64 by 3) double array]
	CurrentAxes = []
	CurrentCharacter =
	CurrentKey =
	CurrentModifier = [ (1 by 0) cell array]
	CurrentObject = []
	CurrentPoint = [0 0]
	DithermapWarning: figure Dithermap is no longer useful
 with TrueColor displays, and will be removed in a future release.
 = [ (64 by 3) double array]
        ...

2. Access the properties’ definition in the handle’s class definition:

>> ch = classhandle(handle(gcf));
>> props = get(ch,'Properties');
>> propsVisibility = get(props,'Visible')';
>> hiddenProps = props(strcmp(propsVisibility,'off'));
>> sort(get(hiddenProps,'Name'))
ans =
    'ALimInclude'
    'ActivePositionProperty'
    'ApplicationData'
    'BackingStore'
    'Behavior'
    'CLimInclude'
    'CurrentKey'
    'CurrentModifier'
    'Dithermap'
    'DithermapMode'
    'ExportTemplate'
    'HelpFcn'
    'HelpTopicKey'
    'HelpTopicMap'
    'IncludeRenderer'
    'JavaFrame'
    'OuterPosition'
    'PixelBounds'
    'PrintTemplate'
    'Serializable'
    'ShareColors'
    'UseHG2'
    'WaitStatus'
    'XLimInclude'
    'YLimInclude'
    'ZLimInclude'

Different HG handles have different hidden properties. Not all these properties are useful. For example, I have found the PixelBounds property to be problematic – (it sometimes reports incorrect values!). Other properties (like Dithermap or ShareColors) are deprecated and display a warning wherever they are accessed.

But every so often we find a hidden property that can be of some actual benefit. Let’s take the figure handle’s OuterPosition property for example. It provides the figure’s external position values, including the space used by the window frame, toolbars etc., whereas the regular documented Position property only reports the internal bounds:

>> get(gcf,'pos')
ans =
   232   246   560   420
>> get(gcf,'outer')
ans =
   228   242   568   502

In future posts I will sometimes use such hidden properties. You can find the latest list by looking at this blog’s “Hidden property” category page.

Note: Like the rest of Matlab’s undocumented items, all hidden properties are undocumented, unsupported and may well change in future Matlab releases so use them with care.

Did you find any useful hidden property? If so, then please leave your finding in the comments section below.

Uicontrol callbacks

Friday, May 1st, 2009

In my previous post I showed how we can extensively customize a Matlab uicontrol’s appearance and behavior by accessing its undocumented underlying Java object. In this post I will show how to further customize the control’s behavior using the callbacks exposed by its underlying object.

Matlab’s uicontrol handles normally expose only a few event callbacks. These are ‘CreateFcn’, ‘DeleteFcn’, ‘ButtonDownFcn’, ‘KeyPressFcn’ and the control-specific ‘Callback’. In contrast, the underlying Java control exposes many more callbacks: 26 standard callbacks, plus a few control-specific callbacks, as follows:

  • AncestorMovedCallback – fired when one of the component’s container ancestors has changed its position relative to its container.
  • AncestorAddedCallback – fired when one of the component’s container ancestors has been added to another container
  • AncestorRemovedCallback – fired when one of the component’s container ancestors has been removed from the component’s hierarchy
  • AncestorResizedCallback – fired when one of the component’s container ancestor has been resized
  • ComponentAddedCallback – fired when a sub-component is added as a direct child to this component. Compare: ComponentRemovedCallback
  • ComponentHiddenCallback – fired when the component is hidden (setVisible(false)). Compare: ComponentShownCallback
  • ComponentMovedCallback – fired when the component is moved within its container. Since Java components are enclosed in a tight-fitting HG container, this callback will never fire for them: it does not fire when the container moves or resizes, only when the component’s starting position is moved within it.
  • ComponentRemovedCallback – fired when a sub-component is added as a direct child to this component. Compare: ComponentAddedCallback
  • ComponentResizedCallback – fired when the component is resized, either directly or because its container was resized.
  • ComponentShownCallback – fired when the component is displayed (setVisible(true)). Compare: ComponentHiddenCallback
  • FocusGainedCallback – fired when the component gains GUI focus, by mouse click, Tab click, or calling the component’s requestFocus() method.
  • FocusLostCallback – fired when the component loses focus to another component or window. Compare: FocusGainedCallback
  • HierarchyChangedCallback – fired when the component changes its ancestors (for example, moved from one panel to another).
  • KeyPressedCallback – fired continuously when any keyboard button (including Shift, Ctrl etc.) was pressed while the component had focus. The meta-data contains details about the specific key and modifiers (Alt, Shift, Ctrl, …) that were pressed. Compare: KeyReleasedCallback, KeyTypedCallback
  • KeyReleasedCallback – fired when a keyboard button was released while the component had focus. The meta-data contains details about the specific key and modifiers (Alt, Shift, Ctrl, …) that were pressed. Compare: KeyPressedCallback
  • KeyTypedCallback – similar to KeyPressedCallback, but only fired (continuously) when an actual printable character is clicked. Therefore, for Shift-A, KeyPressedCallback will fire twice (Shift, ‘A’) but KeyTypedCallback will only fire once. Compare: KeyPressedCallback, KeyReleasedCallback
  • MouseClickedCallback – fired when a mouse button is pressed and then released (=clicked) within the component’s bounds. If either the press or the release occurs outside the component’s bounds, the event will not fire. The figure’s ‘SelectionType’ property will be ‘normal’, ‘extend’ or ‘alt’ depending on which button was pressed. Compare: MousePressedCallback, MouseReleasedCallback.
  • MouseDraggedCallback – fired continuously when the mouse is clicked within the component’s bounds and then moved while the button is still depressed (i.e., dragged), even beyond the component’s bounds. The callback event’s meta-data will contain the delta-x and delta-y of the movement (positive for x-right/y-down; negative for x-left/y-up). Compare: MouseMovedCallback
  • MouseEnteredCallback – fired when the mouse is moved (depressed or not) into the component’s bounds. Compare: MouseExitedCallback
  • MouseExitedCallback – fired when the mouse is moved (depressed or not) out of the component’s bounds. Compare: MouseEnteredCallback
  • MouseMovedCallback – fired continuously when the mouse is moved undepressed within the component’s bounds. The callback event’s meta-data will contain the delta-x and delta-y of the movement (positive for x-right/y-down; negative for x-left/y-up). Compare: MouseDraggedCallback
  • MousePressedCallback – fired immediately when the mouse button is depressed (even before it was released) within the component’s bounds. The callback event’s meta-data will contain the click location within the component’s bounds. Compare: MouseClickedCallback, MouseReleasedCallback
  • MouseReleasedCallback – fired immediately when the mouse button is released within the component’s bounds. The callback event’s meta-data will contain the click location within the component’s bounds. Compare: MousePressedCallback
  • MouseWheelMovedCallback – fired immediately when the mouse wheel is turned (even before it was released) within the component’s bounds.
  • PropertyChangeCallback – fired when one of the component’s properties has changed. For example, after setting the component’s text, tooltip or border. Does not fire when modifying the component’s callback properties.
  • VetoableChangeCallback – fired upon a constrained property value change, allowing the callback to intercept and prevent the property change by raising an exception. Of all the Swing components, only JInternalFrame actually declares vetoable properties which can be intercepted.

It should be noted that these callbacks are standard in all Swing GUI controls. Thus, they can be used not just for Matlab uicontrols’ underlying Java objects, but also for any Swing component that you display using Matlab’s built-in javacomponent function.

The specific list of callbacks supported by each component depends on component type. As noted above, some components have additional specific callbacks. For example, ActionPerformedCallback is fired when a user has performed the main action associated with the control (selecting/clicking etc.). This is one of the most commonly used callbacks, one of the few exposed by Matlab HG handles (as the general-purpose ‘Callback’). This callback is implemented by JButton and JCheckBox (for instance), but not by JList or JMenu. CaretUpdateCallback and CaretPositionChangedCallback are only supported by text-entry controls like JTextField or JEditorPane, but not by JSlider or JTabbedPane. Other components have other such specific callbacks.

To see the full list of supported callbacks for a particular object, use the UIINSPECT utility from the File Exchange or use the following code snippet:

>> props = sort(fieldnames(get(javax.swing.JButton)));
>> callbackNames = props(~cellfun(@isempty,regexp(props,'Callback$')));
callbackNames =
    'ActionPerformedCallback'
    'AncestorAddedCallback'
    'AncestorMovedCallback'
    ...

A nice example of using Java callbacks to automatically select (highlight) the content text in a text-box when focus is gained was one of the first online posts in CSSM to use Matlab 7’s new javacomponent Swing integration.

Another typical usage is to set a continuously-firing callback whenever a slider uicontrol is dragged – the Matlab HG callback only fires once after the drag has completed, whereas we often wish to update some value or graphics during the drag events. This can easily be done using JSlider’s underlying object (a Swing JScrollBar) callbacks.


In order to prevent memory leaks in heavily-laden GUIs, it is advisable to get and set callback properties using the handle object, instead of directly on the “naked” Java reference. For this reason, using set/get is discouraged by MathWorks and may even be disabled in some future Matlab release:

jb = javax.swing.JButton;
jbh = handle(jb,'CallbackProperties');
% or for an existing uicontrol: jbh = findjobj(hButton);
set(jbh, 'ActionPerformedCallback',@myCallbackFcn)  % ok!
set(jb,  'ActionPerformedCallback',@myCallbackFcn)  % bad! memory leak

In some future post I plan to present more details about handle() and its intricacies. But in a nutshell, this code snippet is all you need to start working.

Callbacks can be set in the normal Matlab fashion, using one of three methods:

set(jbh, 'ActionPerformedCallback',@myCallbackFcn);
set(jbh, 'ActionPerformedCallback',{@myCallbackFcn,param1,param2});
set(jbh, 'ActionPerformedCallback','disp(123);');

I would be happy to hear how you use these newly-exposed callbacks in your application. Please leave your welcome comments below.