| MATLAB® | ![]() |
| On this page… |
|---|
Techniques Used in the Example View and Run the Completed GUI M-Files |
This example creates a GUI that displays a user-selected plot in an axes. The GUI contains the following components:
Axes
Pop-up menu with a list of five plots
Push button for updating the contents of the axes
Menu bar File menu with three items: Open, Print, and Close
Toolbar with two buttons that enable a user to open files and print the plot.
When you run the GUI, it initially displays a plot of five random numbers generated by the MATLAB® command rand(5) command, as shown in the following figure.

You can select other plots in the pop-up menu. Clicking the Update button displays the currently selected plot on the axes.
The GUI File menu has three items:
Open displays a dialog from which you can open files on your computer.
Print opens the Print dialog. Clicking Yes in the Print dialog prints the plot.
Close closes the GUI.
The GUI toolbar has two buttons:
The Open button
performs the same function
as the Open menu item. It displays a dialog
from which you can open files on your computer.
The Print button
performs the same function
as the Print menu item. It opens the Print
dialog. Clicking Yes in the Print dialog prints the
plot.
This example illustrates the following techniques:
Passing input arguments to the GUI when it is opened
Obtaining output from the GUI when it returns
Shielding the GUI from accidental changes
Running the GUI across multiple platforms
Creating menus
Creating toolbars
Achieving proper resize behavior
Note This example uses nested functions. For information about using nested functions, see Nested Functions in the MATLAB Programming Fundamentals documentation. |
If you are reading this in the MATLAB Help browser, you can click the following links to display the MATLAB Editor with complete listings of the code used in this example.
Note The following links execute MATLAB commands and are designed to work within the MATLAB Help browser. If you are reading this online or in PDF, you should go to the corresponding section in the MATLAB Help Browser to use the links. |
Click here to display the main GUI M-file in the MATLAB Editor.
Click here to display the utility iconRead M-file in the MATLAB Editor.
Click here to run the GUI with axes, menu, and toolbar.
The example defines two variables mOutputArgs and mPlotTypes.
mOutputArgs is a cell array that holds output values should the user request them. The example later assigns a default value to this argument.
mOutputArgs = {}; % Variable for storing output when GUI returnsmPlotTypes is a 5-by-2 cell array that holds the data to be plotted in the axes. The first column contains the strings that are used to populate the pop-up menu. The second column contains the functions, as anonymous function handles, that create the plots.
mPlotTypes = {... % Example plot types shown by this GUI
'plot(rand(5))', @(a)plot(a,rand(5));
'plot(sin(1:0.01:25))', @(a)plot(a,sin(1:0.01:25));
'bar(1:.5:10)', @(a)bar(a,1:.5:10);
'plot(membrane)', @(a)plot(a,membrane);
'surf(peaks)', @(a)surf(a,peaks)};Because the data is created at the top level of the GUI function, it is available to all callbacks and other functions in the GUI.
See Anonymous Functions in the MATLAB Programming Fundamentals documentation for information about using anonymous functions.
Like the data, the components are created at the top level so that their handles are available to all callbacks and other functions in the GUI.
The following statement creates the figure for GUI.
hMainFigure = figure(... % The main GUI figure
'MenuBar','none', ...
'Toolbar','none', ...
'HandleVisibility','callback', ...
'Color', get(0,...
'defaultuicontrolbackgroundcolor'));The figure function creates the GUI figure.
Setting the MenuBar and Toolbar properties to none, prevents the standard menu bar and toolbar from displaying.
Setting the HandleVisibility property to callback ensures that the figure can be accessed only from within a GUI callback, and cannot be drawn into or deleted from the command line.
The Color property defines the background color of the figure. In this case, it is set to be the same as the default background color of uicontrol objects, such as the Update push button. The factory default background color of uicontrol objects is the system default and can vary from system to system. This statement ensures that the figure's background color matches the background color of the components.
See the Figure Properties reference page for information about figure properties and their default values.
The following statement creates the axes.
hPlotAxes = axes(... % Axes for plotting the selected plot
'Parent', hMainFigure, ...
'Units', 'normalized', ...
'HandleVisibility','callback', ...
'Position',[0.11 0.13 0.80 0.67]);The axes function creates the axes. Setting the axes Parent property to hMainFigure makes it a child of the main figure.
Setting the Units property to normalized ensures that the axes resizes proportionately when the GUI is resized.
The Position property is a 4-element vector that specifies the location of the axes within the figure and its size: [distance from left, distance from bottom, width, height]. Because the units are normalized, all values are between 0 and 1.
Note If you specify the Units property, then the Position property, and any other properties that depend on the value of the Units property, should follow the Units property specification. |
See the Axes Properties reference page for information about axes properties and their default values.
The following statement creates the pop-up menu.
hPlotsPopupmenu = uicontrol(... % List of available types of plot
'Parent', hMainFigure, ...
'Units','normalized',...
'Position',[0.11 0.85 0.45 0.1],...
'HandleVisibility','callback', ...
'String',mPlotTypes(:,1),...
'Style','popupmenu');The uicontrol function creates various user interface controls based on the value of the Style property. Here the Style property is set to popupmenu.
For a pop-up menu, the String property defines the list of items in the menu. Here it is defined as a 5-by-1 cell array of strings derived from the cell array mPlotTypes.
See the Uicontrol Properties reference page for information about properties of uicontrol objects and their default values.
This statement creates the Update push button as a uicontrol object.
hUpdateButton = uicontrol(... % Button for updating selected plot
'Parent', hMainFigure, ...
'Units','normalized',...
'HandleVisibility','callback', ...
'Position',[0.6 0.85 0.3 0.1],...
'String','Update',...
'Callback', @hUpdateButtonCallback);The uicontrol function creates various user interface controls based on the value of the Style property. This statement does not set the Style property because its default is pushbutton.
For a push button, the String property defines the label on the button. Here it is defined as the string Update.
Setting the Callback property to @hUpdateButtonCallback defines the name of the callback function that services the push button. That is, clicking the push button triggers the execution of the named callback. This callback function is defined later in the script.
See the Uicontrol Properties reference page for information about properties of uicontrol objects and their default values.
These statements define the File menu and the three items it contains.
hFileMenu = uimenu(... % File menu
'Parent',hMainFigure,...
'HandleVisibility','callback', ...
'Label','File');
hOpenMenuitem = uimenu(... % Open menu item
'Parent',hFileMenu,...
'Label','Open',...
'HandleVisibility','callback', ...
'Callback', @hOpenMenuitemCallback);
hPrintMenuitem = uimenu(... % Print menu item
'Parent',hFileMenu,...
'Label','Print',...
'HandleVisibility','callback', ...
'Callback', @hPrintMenuitemCallback);
hCloseMenuitem = uimenu(... % Close menu item
'Parent',hFileMenu,...
'Label','Close',...
'Separator','on',...
'HandleVisibility','callback', ...
'Callback', @hCloseMenuitemCallback');The uimenu function creates both the main menu, File, and the items it contains. For the main menu and each of its items, set the Parent property to the handle of the desired parent to create the menu hierarchy you want. Here, setting the Parent property of the File menu to hMainFigure makes it the child of the main figure. This statement creates a menu bar in the figure and puts the File menu on it.
For each of the menu items, setting its Parent property to the handle of the parent menu, hFileMenu, causes it to appear on the File menu.
For the main menu and each item on it, the Label property defines the strings that appear in the menu.
Setting the Separator property to on for the Close menu item causes a separator line to be drawn above this item.
For each of the menu items, the Callback property specifies the callback that services that item. In this example, no callback services the File menu itself. These callbacks are defined later in the script.
See the Uicontrol Properties reference page for information about properties of uicontrol objects and their default values.
These statements define the toolbar and the two buttons it contains.
hToolbar = uitoolbar(... % Toolbar for Open and Print buttons
'Parent',hMainFigure, ...
'HandleVisibility','callback');
hOpenPushtool = uipushtool(... % Open toolbar button
'Parent',hToolbar,...
'TooltipString','Open File',...
'CData',iconRead(fullfile(matlabroot,...
'toolbox\matlab\icons\opendoc.mat')),...
'HandleVisibility','callback', ...
'ClickedCallback', @hOpenMenuitemCallback);
hPrintPushtool = uipushtool(... % Print toolbar button
'Parent',hToolbar,...
'TooltipString','Print Figure',...
'CData',iconRead(fullfile(matlabroot,...
'toolbox\matlab\icons\printdoc.mat')),...
'HandleVisibility','callback', ...
'ClickedCallback', @hPrintMenuitemCallback);The uitoolbar function creates the toolbar on the main figure.
The uipushtool function creates the two push buttons on the toolbar.
The uipushtool TooltipString property assigns a tool tip that displays when the GUI user moves the mouse pointer over the button and leaves it there.
The CData property specifies a truecolor image that displays on the button. For these two buttons, the utility iconRead function supplies the image. If you are reading this in the MATLAB Help browser, click here to display this utility M-file in the MATLAB Editor.
For each of the uipushtools, the ClickedCallback property specifies the callback that executes when the GUI user
clicks the button. Note that the Open push button
and the Print push button
use the same callbacks as their counterpart
menu items.
See Creating Toolbars for more information.
These statements create the plot that appears in the GUI when it first displays, and, if the user provides an output argument when running the GUI, define the output that is returned to the user .
% Update the plot with the initial plot type
localUpdatePlot();
% Define default output and return it if it is requested by users
mOutputArgs{1} = hMainFigure;
if nargout>0
[varargout{1:nargout}] = mOutputArgs{:};
endThe localUpdatePlot function plots the selected plot type in the axes. For a pop-up menu, the uicontrol Value property specifies the index of the selected menu item in the String property. Since the default value is 1, the initial selection is 'plot(rand(5))'. The localUpdatePlot function is a helper function that is defined later in the script, at the same level as the callbacks.
The default output is the handle of the main figure.
This topic defines the callbacks that service the components of the GUI. Because the callback definitions are at a lower level than the component definitions and the data created for the GUI, they have access to all data and component handles.
Although the GUI has six components that are serviced by callbacks,
there are only four callback functions. This is because the Open menu item and the Open toolbar button
share the same callbacks. Similarly,
the Print menu item and the Print
toolbar button
share the same callbacks.
Note These are the callbacks that were specified in the component definitions, Creating the GUI and Its Components. |
The hUpdateButtonCallback function services the Update push button. Clicking the Update button triggers the execution of this callback function.
function hUpdateButtonCallback(hObject, eventdata)
% Callback function run when the Update button is pressed
localUpdatePlot();
endThe localUpdatePlot function is a helper function that plots the selected plot type in the axes. It is defined later in the script, Helper Function: Plotting the Plot Types.
Note MATLAB software automatically passes hUpdateButtonCallback two arguments, hObject and eventdata, because the Update push button component Callback property, @hUpdateButtonCallback, is defined as a function handle. hObject contains the handle of the component that triggered execution of the callback. eventdata is reserved for future use. The function definition line for your callback must account for these two arguments. |
The hOpenMenuitemCallback function services
the Open menu item and the Open toolbar
button
. Selecting the menu item or clicking
the toolbar button triggers the execution of this callback function.
function hOpenMenuitemCallback(hObject, eventdata)
% Callback function run when the Open menu item is selected
file = uigetfile('*.m');
if ~isequal(file, 0)
open(file);
end
endThe hOpenMenuitemCallback function first calls the uigetfile function to open the standard dialog box for retrieving files. This dialog box lists all M-files. If uigetfile returns a filename, the function then calls the open function to open it.

The hPrintMenuitemCallback function services
the Print menu item and the Print
toolbar button
. Selecting the menu item or clicking
the toolbar button triggers the execution of this callback function.
function hPrintMenuitemCallback(hObject, eventdata)
% Callback function run when the Print menu item is selected
printdlg(hMainFigure);
endThe hPrintMenuitemCallback function calls the printdlg function. This function opens the standard dialog box for printing the current figure.

The hCloseMenuitemCallback function services the Close menu item. It executes when the GUI user selects Close from the File menu.
function hCloseMenuitemCallback(hObject, eventdata)
% Callback function run when the Close menu item is selected
selection = ...
questdlg(['Close ' get(hMainFigure,'Name') '?'],...
['Close ' get(hMainFigure,'Name') '...'],...
'Yes','No','Yes');
if strcmp(selection,'No')
return;
end
delete(hMainFigure);
endThe hCloseMenuitemCallback function calls the questdlg function to create and open the question dialog box shown in the following figure.

If the user clicks the No button, the callback returns. If the user clicks the Yes button, the callback deletes the GUI.
See Helper Function: Plotting the Plot Types for a description of the localUpdatePlot function.
The example defines the localUpdatePlot function at the same level as the callback functions. Because of this, localUpdatePlot has access to the same data and component handles.
function localUpdatePlot
% Helper function for plotting the selected plot type
mPlotTypes{get(hPlotsPopupmenu, 'Value'), 2}(hPlotAxes);
endThe localUpdatePlot function uses the pop-up menu Value property to identify the selected menu item from the first column of the mPlotTypes 5-by-2 cell array, then calls the corresponding anonymous function from column two of the cell array to create the plot in the axes.
![]() | Introduction | Color Palette | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |