Write Callbacks Using the Programmatic Workflow

Callbacks for Different User Actions

UI and graphics components have certain properties that you can associate with specific callback functions. Each of these properties corresponds to a specific user action. For example, a uicontrol has a property called Callback. You can set the value of this property to be a handle to a callback function, an anonymous function, or a string containing MATLAB® commands. Setting this property makes your GUI respond when the user interacts with the uicontrol. If the Callback property has no specified value, then nothing happens when the end user interacts with the uicontrol.

This table lists the callback properties that are available, the user actions that trigger the callback function, and the most common UI and graphics components that use them.

Callback Property

User Action

Components That Use This Property

ButtonDownFcn

End user presses a mouse button while the pointer is on the component or figure.

axes, figure, uibuttongroup, uicontrol, uipanel, uitable,

Callback

End user triggers the component. For example: selecting a menu item, moving a slider, or pressing a push button.

uicontextmenu, uicontrol, uimenu

CellEditCallback

End user edits a value in a table whose cells are editable.

uitable

CellSelectionCallback

End user selects cells in a table.

uitable

ClickedCallback

End user clicks the push tool or toggle tool with the left mouse button.

uitoggletool, uipushtool

CloseRequestFcn

The figure closes.

figure

CreateFcn

Callback executes when MATLAB creates the object, but before it is displayed.

axes, figure, uibuttongroup, uicontextmenu, uicontrol, uimenu, uipushtool, uipanel, uitable, uitoggletool, uitoolbar

DeleteFcn

Callback executes just before MATLAB deletes the figure.

axes, figure, uibuttongroup, uicontextmenu, uicontrol, uimenu, uipushtool, uipanel, uitable, uitoggletool, uitoolbar

KeyPressFcn

End user presses a keyboard key while the pointer is on the object.

figure, uicontrol, uipanel, uipushtool, uitable, uitoolbar

KeyReleaseFcn

End user releases a keyboard key while the pointer is on the object.

figure, uicontrol, uitable

OffCallback

Executes when the State of a toggle tool changes to 'off'.

uitoggletool

OnCallback

Executes when the State of a toggle tool changes to 'on'.

uitoggletool

SizeChangedFcn

End user resizes a button group, figure, or panel whose Resize property is 'on'.

figure, uipanel, uibuttongroup

SelectionChangedFcn

End user selects a different radio button or toggle button within a button group.

uibuttongroup

WindowButtonDownFcn

End user presses a mouse button while the pointer is in the figure window.

figure

WindowButtonMotionFcn

End user moves the pointer within the figure window.

figure

WindowButtonUpFcn

End user releases a mouse button.

figure

WindowKeyPressFcn

End user presses a key while the pointer is on the figure or any of its child objects.

figure

WindowKeyReleaseFcn

End user releases a key while the pointer is on the figure or any of its child objects.

figure

WindowScrollWheelFcn

End user turns the mouse wheel while the pointer is on the figure.

figure

How to Specify Callback Property Values

To associate a callback function with a UI component, set the value of one of the component's callback properties to be a reference to the callback function. Typically, you do this when you define the component, but you can change callback property values anywhere in your code.

Specify the callback property value in one of these ways:

Specify a Function Handle

Function handles provide a way for you to represent a function as a variable. You define the function as a local or nested function in the same file as the GUI code, or you can write it in a separate program file that is on the MATLAB path. The function definition must define two input arguments, hObject and callbackdata. Handle Graphics® automatically passes hObject and callbackdata when it calls the function. For more information about these arguments, see Callback Syntax.

This code creates a slider component and specifies its callback as a function handle. To see how it works, copy and paste this code into an editor and run it.

function mygui()
   figure
   uicontrol('Style','slider','Callback',@display_slider_value);
end
function display_slider_value(hObject,callbackdata)
   newval = num2str(hObject.Value);
   disp(['Slider moved to ' newval]);
end

This callback function displays the value of the slider when the end user adjusts it. A benefit of specifying callbacks as function handles is that MATLAB checks the function for syntax errors and missing dependencies when you assign the callback to the component. If there is a problem in the callback function, then MATLAB returns an error immediately instead of waiting for the end user to trigger the callback. This behavior helps you to find problems in your code before the end user encounters them.

    Note:   If you want to use an existing function that does not support the hObject and callbackdata arguments, then you can specify it as an anonymous function. For example,
    uicontrol('Style','slider','Callback',@(hObject,callbackdata)myfunction(x));

    In this case, x is an input argument to the function, myfunction. See Anonymous Functions for more information.

Specify a Cell Array

Use a cell array to specify a callback function that accepts input arguments that you want to use in the function. The first element in the cell array is a function handle. The other elements in the cell array are the input arguments to the function, separated by commas. For example, this code creates a push button component and specifies its callback to be a cell array containing the function handle, @pushbutton_callback, and one input argument, myvar. To see how it works, copy and paste this code into an editor and run it.

function somegui()
   myvar = 5;
   figure
   uicontrol('Style','pushbutton',...
             'Callback',{@pushbutton_callback,myvar});
end
function pushbutton_callback(hObject,callbackdata,x)
   display(x);
end

The function definition must define two input arguments, hObject and callbackdata, followed by any additional arguments the function uses. Handle Graphics automatically passes the hObject and callbackdata arguments when it calls the function. If you define additional input arguments, then the values you pass to the callback must exist in the workspace when the end user triggers the callback.

Like callbacks specified as function handles, MATLAB checks callbacks specified as cell arrays for syntax errors and missing dependencies when you assign the callback to the component. If there is a problem in the callback function, then MATLAB returns an error immediately instead of waiting for the end user to trigger the callback. This behavior helps you to find problems in your code before the end user encounters them.

Specify a String of MATLAB Commands (Not Recommended)

You can use string callbacks for a few simple commands, but the callback can become difficult to manage if it contains more than a few commands. The string you specify must consist of valid MATLAB expressions, which can include arguments to functions. For example:

hb = uicontrol('Style','pushbutton',...
               'String','Plot line',...
               'Callback','plot(rand(20,3))');

The callback string, 'plot(rand(20,3))', is a valid command, and MATLAB evaluates it when the end user clicks the button. If the callback string includes a variable, for example,

'plot(myvar)'

The variable, myvar, must exist in the base workspace when the end user triggers the callback, or it returns an error. The variable does not need to exist at the time you assign callback property value, but it must exist when the end user triggers the callback.

Unlike callbacks that are specified as function handles or cell arrays, MATLAB does not check string callbacks for syntax errors or missing dependencies. If there is a problem with the code in your string, it remains undetected until the end user triggers the callback.

Callback Syntax

All callback functions that you reference as function handles or cell arrays must accept the at least two input arguments, hObject and callbackdata. All other input arguments must appear after hObject and callbackdata in the function definition.

The hObject argument is a handle to the UI component that triggered the callback. The callbackdata argument provides additional information to certain callback functions. For example, if the end user triggers the KeyPressFcn, then MATLAB provides information regarding the specific key (or combination of keys) that the end user pressed. If callbackdata is not available to the callback function, then MATLAB passes it as an empty array. The following table lists the callbacks and components that use callbackdata.

Callback Property NameComponent
WindowKeyPressFcn
WindowKeyReleaseFcn
WindowScrollWheel
figure
KeyPressFcnfigure, uicontrol, uitable
KeyReleaseFcnfigure, uicontrol, uitable
SelectionChangedFcnuibuttongroup
CellEditCallback
CellSelectionCallback
uitable

Was this topic helpful?