Creating Graphical User Interfaces |
Adding Code to the Opening Function
The Opening Function
The opening function is the first callback in every GUI M-file. You can use it to perform tasks that need to be done before the user has access to the GUI, for example, to create data or to read data from an external source.The code in the opening function is executed just before the GUI is made visible to the user, but after all the components have been created.
In this example, you add code that creates three data sets in the opening function, using the MATLAB functions peaks
, membran
e, and sinc
.
Note that GUIDE names the opening function with the name of the M-file prefixed to _OpeningFcn
. In this example, the M-file is named simple_gui.m
, so that the opening function is named simple_gui_OpeningFcn
.
For more information about the opening function see Opening Function.
Adding the Code
To create data for the GUI to plot, add the following code to the opening function immediately after the comments following the function declaration.
% --- Executes just before simple_gui is made visible.
function simple_gui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to untitled (see VARARGIN)
% Create the data to plot
handles.peaks=peaks(35); handles.membrane=membrane; [x,y] = meshgrid(-8:.5:8); r = sqrt(x.^2+y.^2) + eps; sinc = sin(r)./r; handles.sinc = sinc; handles.current_data = handles.peaks; surf(handles.current_data)
The first six executable lines create the data using the MATLAB functions peaks
, membrane
and sinc
to generate the data.
The next line, handles.current_data = handles.peaks
, sets the current_data
field of the handles structure equal to the data for peaks. In the example GUI, the pop-up menu displays peaks
as the initial selection. The value of handles.current_data
changes each time a user selects a different plot from the pop-up menu -- see Pop-up Menu Callback.
The last line displays the surf plot for peaks, which appears when the GUI is first opened.
GUIDE automatically generates two more lines of code in the opening function, which follow the code that you add:
handles.output = hObject
saves the handle to the GUI for later access by the output function. While this command is not necessary in this example, it is useful if you want to return the GUI handle to the command line. For more information about the output function see Output Function.
guidata(hObject,handles)
saves the handles
structure.
The following figure shows how the GUI now looks when it first displays.
Sharing Data Between Callbacks | Adding Code to the Callbacks |
© 1994-2005 The MathWorks, Inc.