| Creating Graphical User Interfaces | ![]() |
GUIDE provides a mechanism for storing and retrieving data using application-defined data stored on the GUI figure. GUIDE uses this mechanism to save a structure containing the handles of all the components in the GUI. Since this structure is passed to each callback subfunction, it is useful for saving other data as well, as is illustrated by the following example.
Passing Data in the Handles Structure
This example demonstrates how to use the handles structure to pass data between callback routines.
Suppose you want to create a GUI containing a slider and an editable text box that behave as follows:
This picture shows the GUI with a static text field above the edit text box.
Defining the Data Fields During Initialization
The following excerpt from the GUI setup code show two additional fields defined in the handles structure - errorString and numberOfErrors:
guihandles creates the structure and adds the handles of the slider and edit text using the Tag property to name the fields (edit1 and slider1).guidata stores the structure in the figure's application data.fig = openfig(mfilename,'reuse'); handles = guihandles(fig); handles.errorString = 'Total number of errors: '; handles.numberOfErrors = 0; guidata(fig,handles);
Setting the Edit Text Value from the Slider Callback
Use the handles structure to obtain the handles of the edit text and the slider and then set the edit text String to the slider Value.
set(handles.edit1,'String',...num2str(get(handles.slider1,'Value')));
Setting the Slider Value from the Edit Text Callback
The edit text callback routine sets the slider's value to the number the user types in, after checking to see if it is a single numeric value within the range of values allowed by the slider. If the value is out of range, then the error count is incremented and the error string and the error count are displayed.
val = str2num(get(handles.edit1,'String'));
if isnumeric(val) & length(val)==1 & ...
val >= get(handles.slider1,'Min') & ...
val <= get(handles.slider1,'Max')
set(handles.slider1,'Value',val);
else
% Increment the error count, and display it
handles.numberOfErrors = handles.numberOfErrors+1;
set(handles.edit1,'String',...
[handles.errorString,num2str(handles.numberOfErrors)]);
guidata(gcbo,handles); % store the changes...
Updating GUI Data. Note that you must use guidata to save the handles structure whenever you change values in that structure. The statement,
guidata(gcbo,handles);
makes use of the fact that guidata can determine the parent figure automatically from the handle of any child object (gcbo here). This is useful when you disable Command-line accessibility in the Application Options Dialog (the default); you cannot use findobj to obtain the figure handle.
| Initializing the GUI | If You Are Not Using a Handle Structure | ![]() |