MATLAB Creating Graphical User Interfaces

(ff) #1

Callbacks for Specific Components


Coding the behavior of a UI component involves specific tasks that are unique to the type
of component you are working with. This topic contains simple examples of callbacks for
each type of component. The examples are written for GUIDE unless otherwise stated.
For general information about coding callbacks, see “Write Callbacks in GUIDE” on page
7-2 or “Write Callbacks for Apps Created Programmatically” on page 10-5.

How to Use the Example Code


If you are working in GUIDE, then right-click on the component in your layout and select
the appropriate callback property from the View Callbacks menu. Doing so creates an
empty callback function that is automatically associated with the component. The specific
function name that GUIDE creates is based on the component’s Tag property, so your
function name might be slightly different than the function name in the example code. Do
not change the function name that GUIDE creates in your code. To use the example code
in your app, copy the code from the example’s function body into your function’s body.

If you are creating an app programmatically, (without GUIDE), then you can adapt the
example code into your code. To adapt an example into your code, omit the third input
argument, handles, from the function definition. Also, replace any references to the
handles array with the appropriate object handle. To associate the callback function
with the component, set the component's callback property to be a handle to the callback
function. For example, this command creates a push button component and sets the
Callback property to be a handle to the function, pushbutton1_callback.
pb =
uicontrol('Style','pushbutton','Callback',@pushbutton1_Callback);

Push Button


This code is an example of a push button callback function in GUIDE. Associate this
function with the push button Callback property to make it execute when the end user
clicks on the push button.

function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
display('Goodbye');
close(gcf);

7 Programming a GUIDE App

Free download pdf