MATLAB Creating Graphical User Interfaces

(Barry) #1
Share Data Among Callbacks

Method Description Requirements and Trade-Offs
UIs)” on page
12-5


  • Can share multiple variables.


“Store Data
Using the
guidata
Function” on
page 12- 6

Share data with the figure window
using the guidata function.


  • Stores or retrieves the data
    through any UI component.

  • Stores only one variable at
    a time, but you can store
    multiple values as a struct
    array or cell array.


Store Data in UserData or Other Object Properties


UI components contain useful information in their properties, which you can access
directly as long as you have access to the component. If you do not have access to the
component, then use the findobj function to search for the component that has a known
property value. You can store any data in the UserData property of a UI component or
figure. For example, the following programmatic UI code uses the UserData property to
share information about the slider. To see how it works, copy and paste this code into an
editor and run it.


function my_slider()
hfig = figure();
slider = uicontrol('Parent', hfig,'Style','slider',...
'Units','normalized',...
'Position',[0.3 0.5 0.4 0.1],...
'Tag','slider1',...
'UserData',struct('val',0,'diffMax',1),...
'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);
end


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

Free download pdf