MATLAB Creating Graphical User Interfaces

(Barry) #1
Write Callbacks Using the Programmatic Workflow

Callback Property User Action Components That Use This Property
WindowKeyReleaseFcnEnd user releases a key while the
pointer is on the figure or any of
its child objects.

figure

WindowScrollWheelFcnEnd 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” on page 11-7.

  • “Specify a Cell Array” on page 11-8. This cell array contains a function handle
    as the first element, followed by and any input arguments you want to use in the
    function.

  • “Specify a String of MATLAB Commands (Not Recommended)” on page 11- 9


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 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” on page 11-9.


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 myui()
figure
uicontrol('Style','slider','Callback',@display_slider_value);
end
function display_slider_value(hObject,callbackdata)
newval = num2str(hObject.Value);

Free download pdf