Skip to Main Content Skip to Search
Product Documentation

GUI with Axes, Menu, and Toolbar

About the Axes, Menu, and Toolbar Example

This example creates a GUI that displays a user-selected plot in an axes. The GUI contains the following components:

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.

plot of five random numbers

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:

The GUI toolbar has two buttons:

This example illustrates the following GUI-building techniques:

View and Run the AxesMenuToolbar Code

If you are reading this example example in the MATLAB Help browser, you can access the example code files by clicking the following links. If you are reading on the Web or in a PDF, go to the corresponding section in the MATLAB Help Browser to use the links.

If you intend to modify the layout or code of this GUI example, you should first save a copy of its code in your current folder (You need write access to your current folder to do this.) Click on the following links to copy the example files to your current folder and open them.

  1. Click here to copy the code files to your current folder

  2. edit axesMenuToolbar.m or click here to open the GUI code in the Editor

  3. edit iconRead.m or Click here to open the utility iconRead file in the Editor .

If you just want to run the GUI and inspect its code, follow these steps:

  1. Click here to add the example files to the MATLAB path (only for the current session).

  2. Click here to run the axesMenuToolbar GUI.

  3. Click here to display the axesMenuToolbar code in the Editor (read-only).

  4. Click here to display the utility iconRead file in the Editor (read-only).

Generate the Graphing Commands and Data

The example defines two variables mOutputArgs and mPlotTypes.

mOutputArgs is a cell array that holds output values should the user request them to be returned. The example later assigns a default value to this argument.

mOutputArgs = {};  % Variable for storing output when GUI returns

mPlotTypes is a 5-by-2 cell array that specifies graphing functions and data for them, both as strings and as anonymous functions. 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.

For information about using anonymous functions, see Anonymous Functions .

Create the GUI and Its Components

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 Main Figure

The following statement creates the figure for GUI.

hMainFigure = figure(...       % The main GUI figure
                    'MenuBar','none', ...
                    'Toolbar','none', ...
                    'HandleVisibility','callback', ...
                    'Color', get(0,...
                             'defaultuicontrolbackgroundcolor'));

See the Figure Properties reference page for information about figure properties and their default values.

The Axes

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]);

See the Axes Properties reference page for information about axes properties and their default values.

The Pop-Up Menu

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');

See the Uicontrol Properties reference page for information about properties of uicontrol objects and their default values.

The Update Push Button

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);

See the Uicontrol Properties reference page for information about properties of uicontrol objects and their default values.

The File Menu and Its Menu Items

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);

See the Uicontrol Properties reference page for information about properties of uicontrol objects and their default values.

The Toolbar and Its Tools

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);

See Create Toolbars for Programmatic GUIs for more information.

Initialize the GUI

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{:};
end

Define the Callbacks

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.

Update Button Callback

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();
  end

The localUpdatePlot function is a helper function that plots the selected plot type in the axes. It is defined later in the script, Helper Function: Plot the Plot Types.

Open Menu Item Callback

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
end

The hOpenMenuitemCallback function first calls the uigetfile function to open the standard dialog box for retrieving files. This dialog box lists all files having the extension .m. If uigetfile returns a file name, the function then calls the open function to open it.

Print Menu Item Callback

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);
end

The hPrintMenuitemCallback function calls the printdlg function. This function opens the standard system dialog box for printing the current figure. Your print dialog box might look different than the one shown here.

Close Menu Item Callback

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);
end

The 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: Plot the Plot Types for a description of the localUpdatePlot function.

Helper Function: Plot the Plot Types

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);
end

The 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.

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS