Callbacks: An Overview

What Is a Callback?

A callback is a function that you write and associate with a specific component in the GUI or with the GUI figure itself. The callbacks control GUI or component behavior by performing some action in response to an event for its component. The event can be a mouse click on a push button, menu selection, key press, etc. This kind of programming is often called event-driven programming.

The callback functions you provide control how the GUI responds to events such as button clicks, slider movement, menu item selection, or the creation and deletion of components. There is a set of callbacks for each component and for the GUI figure itself.

The callback routines usually appear in the M-file following the initialization code and the creation of the components. See File Organization for more information.

When an event occurs for a component, MATLAB software invokes the component callback that is associated with that event. As an example, suppose a GUI has a push button that triggers the plotting of some data. When the user clicks the button, the software calls the callback you associated with clicking that button, and then the callback, which you have programmed, gets the data and plots it.

A component can be any control device such as an axes, push button, list box, or slider. For purposes of programming, it can also be a menu, toolbar tool, or a container such as a panel or button group. See Available Components for a list and descriptions of components.

Kinds of Callbacks

The GUI figure and each type of component has specific kinds of callbacks with which you can associate it. The callbacks that are available for each component are defined as properties of that component. For example, a push button has five callback properties: ButtonDownFcn, Callback, CreateFcn, DeleteFcn, and KeyPressFcn. A panel has four callback properties: ButtonDownFcn, CreateFcn, DeleteFcn, and ResizeFcn. You can, but are not required to, create a callback function for each of these properties. The GUI itself, which is a figure, also has certain kinds of callbacks with which it can be associated.

Each kind of callback has a triggering mechanism or event that causes it to be called. The following table lists the callback properties that are available, their triggering events, and the components to which they apply. Links in the first column lead to documentation search results for each type of callback. These links only operate when you are using the MATLAB Help Browser.

Callback Property

Triggering Event

Components

ButtonDownFcn

Executes when the user presses a mouse button while the pointer is on or within five pixels of a component or figure.

Axes, figure, button group, panel, user interface controls

Callback

Control action. Executes, for example, when a user clicks a push button or selects a menu item.

Context menu, menu user interface controls

CellEditCallback

Reports any edit made to a value in a table with editable cells; uses event data.

uitable

CellSelectionCallback

Reports indices of cells selected by mouse gesture in a table; uses event data.

uitable

ClickedCallback

Control action. Executes when the push tool or toggle tool is clicked. For the toggle tool, this is independent of its state.

Push tool, toggle tool

CloseRequestFcn

Executes when the figure closes.

Figure

CreateFcn

Initializes the component when it is created. It executes after the component or figure is created, but before it is displayed.

Axes, button group, context menu, figure, menu, panel, push tool, toggle tool, toolbar, user interface controls

DeleteFcn

Performs cleanup operations just before the component or figure is destroyed.

Axes, button group, context menu, figure, menu, panel, push tool, toggle tool, toolbar, user interface controls

KeyPressFcn

Executes when the user presses a keyboard key and the callback's component or figure has focus.

Figure, user interface controls

KeyReleaseFcn

Executes when the user releases a keyboard key and the figure has focus.

Figure

OffCallback

Control action. Executes when the State of a toggle tool is changed to off.

Toggle tool

OnCallback

Control action. Executes when the State of a toggle tool is changed to on.

Toggle tool

ResizeFcn

Executes when a user resizes a panel, button group, or figure whose figure Resize property is set to On.

Figure, button group, panel

SelectionChangeFcn

Executes when a user selects a different radio button or toggle button in a button group component.

Button group

WindowButtonDownFcn

Executes when you press a mouse button while the pointer is in the figure window.

Figure

WindowButtonMotionFcn

Executes when you move the pointer within the figure window.

Figure

WindowButtonUpFcn

Executes when you release a mouse button.

Figure

WindowKeyPressFcn

Executes when you press a key when the figure or any of its child objects has focus.

Figure

WindowKeyReleaseFcn

Executes when you release a key when the figure or any of its child objects has focus.

Figure

WindowScrollWheelFcn

Executes when the mouse wheel is scrolled while the figure has focus.

Figure

Providing Callbacks for Components

A GUI can have many components and each component's properties provide a way of specifying which callback should run in response to a particular event for that component. The callback that runs when the user clicks a Yes button is usually not the one that runs for the No button. Each menu item also performs a different function and needs its own callback.

You attach a callback to a specific component by setting the value of the component's callback property (described in the previous table) to the callback as a property/value pair. The property identifies the callback type and the value identifies a function to perform it. You can do this when you define the component or later on in other initialization code. In some cases, you can change callbacks while the GUI is being used.

Specify a component callback property value as one of the following:

You can attach a callback when you create a component by supplying the callback's property name and value (its calling sequence). You can also add or replace a callback at a later time using the set command. The examples that follow all use set, a recommended practice because some of the parameters a callback specifies might not exist or have the required values at the time a component is created.

Using String Callbacks

String callbacks are the easiest type to create, because they are self-contained. They also reside in the figure itself rather than in an M-file. You can use string callbacks for simple purposes, but they become cumbersome if the callback action does more than one thing. Strings used for callbacks must be valid MATLAB expressions or commands, including built-in or M-file functions, and can include arguments to the function. For example:

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

The callback string 'plot(rand(20,3))', a valid MATLAB command, is evaluated whenever the button is clicked. If you then change the callback to plot a variable, for example:

set(hb,'Callback','plot(myvar)')

then the variable myvar must exist in the base workspace at the time that the callback is triggered or the callback causes an error. It does not need to exist at the time the callback is attached to the component, only when it is triggered. For some details about workspaces, see Scope of a Variable in the MATLAB Programming Fundamentals documentation and the evalin function reference page.

You can concatenate commands in a string callback. This one, for example, adds a title to the plot it creates.

set(hb,'Callback',...
       'plot(myvar,''--m''); title(''String Callback'')')

Using Cell Array Callbacks

This type of callback specifies a function and usually arguments to be passed to it. For example, here is a cell array callback defined as having an M-function name as a quoted string, 'pushbutton_callback', and two arguments, one a variable name and one a string:

myvar = rand(20,1);
set(hb,'Callback',{'pushbutton_callback',myvar,'--m'})

You must place the function name first in the cell array and specify it as a string. When this form of callback is triggered, MATLAB executes an M-file having the name of the first element in the cell array, passing it two standard arguments followed by any additional elements of the cell array that you specify. The function must exist on the MATLAB path, and needs to have at least two arguments. The first two (which MATLAB automatically inserts) are

These two arguments are followed by whatever arguments you include when you specify the callback for the component. Code to execute 'pushbutton_callback' might look like this:

function pushbutton_callback(hObject, eventdata, var1, var2)
plot(var1,var2)

The arguments you define can be variables, constants, or strings. If you use set to specify a callback, any variables it uses as arguments must exist in the current workspace at the time you set the callback. In the above example, the value of the first argument (variable myvar) is copied into the callback when setting it. Consequently, if myvar does not currently exist, you receive an error:

??? Undefined function or variable 'myvar'.

If myvar changes or is deleted after defining the callback, the original value will still be used.

The second argument ('--m') is a string literal LineSpec that does not refer to any variable and, therefore, cannot raise an error when you specify the callback.

To use this GUI, create an M-file called pushbutton_callback.m containing the following code:

function pushbutton_callback(hObject, eventdata, var1, var2)
plot(var1,var2)

When you run this GUI by pressing the push button, you see a line graph of myvar appearing as a magenta dashed line, similar to the following (graphs can differ due to using the rand function to generate data).


Because the value of myvar was copied into the callback when it was set, clicking the button always produces the same plot, even if the value of myvar changes in the base workspace.

See Defining Callbacks as a Cell Array of Strings — Special Case in the MATLAB Graphics documentation for more information.

Using Cell Arrays with Function Handles.   You can specify a callback function using a function handle instead of using a function name. The major benefit to using function handles is the capability to define functions on the fly—in executing M-code that sets a component's callback to the handle of a function defined within its scope, for example, an anonymous function. Dynamic callback assignment enables callbacks to change their behavior according to the context within which they operate or data they process.

The following variation uses a function handle to specify pushbutton_callback as the callback routine to be executed when a user clicks Plot line.

figure;
hb = uicontrol('Style','pushbutton',...
               'String','Plot line')
set(hb,'Callback',{@pushbutton_callback,myvar,'--m'})

Callback is the name of the callback property. The first element of the cell array is the handle of the callback routine, and subsequent elements are input arguments to the callback. Since a function handle is not a string, do not place it within quotes. The second and third elements of the cell array, the variable myvar and the string '--m', become the third and fourth argument of the callback, after hObject and eventdata.

As above, the callback is in an M-file named pushbutton_callback.m, which contains code such as this:

function pushbutton_callback(hObject, eventdata, var1, var2)
plot(var1,var2)

As you can see from the previous examples, you can specify either a function name or a function handle in a callback using a cell array and achieve the same results. Using function handles gives you additional flexibility when your application needs to behave dynamically.

For more information on using function handles, see Introduction in the MATLAB Graphics documentation. See Kinds of Callbacks for a summary of available callbacks. See the component property reference pages for information about the specific types of callbacks each type of component supports.

Sharing Callbacks Among Components

If you are designing a GUI and programming it yourself (outside of GUIDE), you can attach the same callback to more than one component. This is a good technique to use when a group of controls perform similar actions with small variations or operate identically on different data. In such cases, you can design a single callback function that provides separate code paths to handle each case. The callback can decide what code path to take based on the identity and type of object that calls it, or on the basis of parameters passed into it.

For an example of a callback shared by three check boxes that plot three different columns of tabular data, see GUI that Displays and Graphs Tabular Data. All three components do the same thing; the last argument in their common callback provides the number of the column to retrieve data from when plotting.

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS