MATLAB Creating Graphical User Interfaces

(Barry) #1

12 Manage Application-Defined Data


the slider position. To see how it works, copy and paste this code into an editor and run
it.

function my_slider()
hfig = figure();
data = struct('val',0,'diffMax',1);
slider = uicontrol('Parent', hfig,'Style','slider',...
'Units','normalized',...
'Position',[0.3 0.5 0.4 0.1],...
'Tag','slider1',...
'Callback',@slider_callback);

button = uicontrol('Parent', hfig,'Style','pushbutton',...
'Units','normalized',...
'Position',[0.4 0.3 0.2 0.1],...
'String','Display Difference',...
'Callback',@button_callback);

function slider_callback(hObject,eventdata)
sval = hObject.Value;
diffMax = hObject.Max - sval;
data.val = sval;
data.diffMax = diffMax;
end

function button_callback(hObject,eventdata)
display([data.val data.diffMax]);
end
end
The main function defines a struct array called data. When the user moves the slider,
the slider_callback function updates the val and diffMax fields of the data
structure. When the end user clicks the push button, the button_callback function
displays the values stored in data.

Note:Nested functions are not recommended for GUIDE UIs.

Store Data Using the guidata Function


The guidata function provides a way to share data with the figure window. You can
store or retrieve the your data in any callback through the hObject component. This
means that, unlike working with UserData or application data, you do not have to
Free download pdf