Axes, Menus, and Toolbars in Programmatic GUIs

About the Example

When you run this GUI, it initially displays a plot of five random numbers generated by the MATLAB® rand(5) command.

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

  • 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 option. It displays a dialog from which you can open files on your computer.

  • The Print button performs the same function as the Print menu option. It opens the Print dialog. Clicking Yes in the Print dialog prints the plot.

View the Example Code

To obtain copies of the GUI files for this example, follow these steps:

  1. Set your current folder to one to which you have write access.

  2. Copy the example code and display the example code files in the Editor by executing these MATLAB commands:

    copyfile(fullfile(docroot, 'techdoc','creating_guis',...
     'examples','axesMenuToolbar.m')),...
      fileattrib('axesMenuToolbar.m', '+w');
    copyfile(fullfile(docroot, 'techdoc','creating_guis',...
    'examples','iconRead.m')),fileattrib('iconRead.m', '+w');
    edit axesMenuToolbar.m
    edit iconRead.m

Generate the Graphing Commands and Data

The program file, axesMenuToolbar.m, defines two variables mOutputArgs and mPlotTypes.

mOutputArgs is a cell array that holds output values that are optionally returned by the function.

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

mPlotTypes is a 5-by-2 cell array that specifies graphing functions and data. The first column contains the strings that are used to populate the pop-up menu. The second column contains functions (anonymous functions) for creating 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 these variables are created in the main function, they are accessible from within the nested callback functions in the same file.

Create the GUI and Its Components

Like the mOutputArgs and mPlotTypes variables, the UI components are created inside the main function, so they are accessible from within the nested callback functions in the same file.

The Main Figure

This command creates the figure window:

hMainFigure = figure(...       % The main GUI figure
                    'MenuBar','none', ...
                    'Toolbar','none', ...
                    'HandleVisibility','callback', ...
                    'Color', get(groot,...
                             'defaultuicontrolbackgroundcolor'));
  • Setting the MenuBar and Toolbar properties to 'none' prevents the default menus from displaying and hides the default toolbar.

  • Setting the HandleVisibility property to 'callback' ensures that the figure object can be accessed only from within a GUI callback.

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

The Axes

This command 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 user resizes the figure window.

  • 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].

The Pop-Up Menu

This command 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.

The Update Push Button

This command creates the Update push button:

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 specifies the function, hUpdateButtonCallback to be the function that executes when the user presses the push button. This callback function is a nested function in the same file.

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);
  • The uimenu function creates both the main menu, File, and the menu items under it. 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.

  • The Label property defines the text label for each menu item.

  • Setting the Separator property to 'on' for creates a separator line above a menu item.

  • For each of the menu items, the Callback property specifies the callback that services that item. These callbacks are defined as nested functions in the same file.

The Toolbar

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.

  • The uipushtool function creates the two push buttons in the toolbar.

  • The uipushtool TooltipString property assigns a tool tip that displays when the 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.

  • For each of the uipushtools, the ClickedCallback property specifies the callback that executes when the user clicks the buttons.

Initialize the GUI

This code creates the plot that appears when the GUI initially displays. This code also checks to see if the user provided an output argument.

% 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
  • The localUpdatePlot function creates a plot in the axes. The localUpdatePlot function gets the pop-up menu's Value property to determine which plot the user selected.

  • The default output argument is the handle of the main figure.

Define the Callbacks

This topic defines the callbacks that service the components of the GUI. Because the callback definitions are nested, they have access to all data and components defined in the main function.

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

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 .fig. 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 ' hMainFigure.Name '?'],...
                ['Close ' 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 GUI user clicks the Yes button, the callback deletes the GUI.

Updating the Plot

Here is the code for the localUpdatePlot function. Because it is a nested function, localUpdatePlot has access to the same data and UI components as the other callback functions.

function localUpdatePlot
% Helper function for plotting the selected plot type
    mPlotTypes{hPlotsPopupmenu.Value, 2}(hPlotAxes);
end

The localUpdatePlot function gets 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, localUpdatePlot calls the corresponding anonymous function from the second column in the cell array.

See Also

| |

More About

Was this topic helpful?