User`s guide
12 Code a Programmatic GUI
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 e xamples 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.
Use String Callbacks
String callbacks are the easiest type to create, because they are self-contained.
They also reside in the GUI figure itself rather than in a code file. You can
use string callbacks for simple purposes, but they become cumbersome if the
callback action does more than one thing or requires more than one or two
parameters. Strings used for callbacks must be valid M ATLA B express ions,
or built-in or file-based functions, and can include arguments to functions.
For example:
hb = uicontrol('Style','pushbutton ',...
'String','Plot line')
set(hb,'Callback','plot(rand(20,3)) ')
The callback string 'plot(rand(20,3))',avalidMATLABcommand,is
evaluated whenever the button is clicked. If you then change the callback to
plot a variable, fo r 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. Before using the callback, your code can declare it:
myvar = rand(20,1);
String callbacks are the only type of callback that do not require arguments
to exist as variables when they are defined. Arguments to function handle
callbacks are evaluated when you define them, and therefore must exist at
that time.
For some details about w orkspaces, see “Share Data Between W orkspaces”
and the
evalin function reference page.
12-12