GUI with Axes, Menu, and Toolbar

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

Techniques Used in the Example

This example illustrates the following techniques:

View and Run the Completed GUI M-Files

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.

Creating the Data

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 returns

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

Creating 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 Creating Toolbars for more information.

Initializing 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

Defining 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: Plotting 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 M-files. If uigetfile returns a filename, 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 dialog box for printing the current figure.

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

Helper Function: Plotting 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.

  


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