Quantcast

Documentation Center

  • Trial Software
  • Product Updates

Create a Simple Programmatic GUI

This example shows how to create a simple programmatic GUI, such as shown in the following figure.

Subsequent topics guide you through the process of creating this GUI.

If you prefer to view and run the code that created this GUI without creating it, set your current folder to one to which you have write access. Copy the example code and open it in the Editor by issuing the following MATLAB® commands:

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

To run the GUI, on the Editor tab, in the Run section, click Run .

Create a Code File for the Simple Programmatic GUI

Create a function file (as opposed to a script file, which contains a sequence of MATLAB commands but does not define functions).

  1. At the MATLAB prompt, type edit.

  2. Type the following statement in the first line of the Editor.

    function simple_gui2
  3. Following the function statement, type these comments, ending with a blank line. (The comments display at the command line in response to the help command.)

    % SIMPLE_GUI2 Select a data set from the pop-up menu, then
    % click one of the plot-type push buttons. Clicking the button
    % plots the selected data in the axes.
    (Leave a blank line here)
  4. At the end of the file, after the blank line, add an end statement.

      Note   You need the end statement to specify the end of the function because the example uses nested functions. To learn more, see Nested Functions.

  5. Save the file in your current folder or at a location that is on your MATLAB path.

Create a Figure for the Simple Programmatic GUI

Add the following lines before the end statement in your file to create a figure and position it on the screen. (In MATLAB software, a GUI is a figure. )

%  Create and then hide the GUI as it is being constructed.
f = figure('Visible','off','Position',[360,500,450,285]);

The call to the figure function uses two property/value pairs:

  • The Visible property makes the GUI invisible so that the GUI user cannot see the components being added or initialized.

    When the GUI has all its components and is initialized, the example makes it visible.

  • The Position property is a four-element vector that specifies the location of the GUI on the screen and its size: [distance from left, distance from bottom, width, height]. Default units are pixels.

Add Components to the Simple Programmatic GUI

Create the push buttons, static text, pop-up menu, and axes components to the GUI.

  1. Following the call to figure, add these statements to your code file to create three push button components.

    % Construct the components.
    hsurf    = uicontrol('Style','pushbutton',...
                 'String','Surf','Position',[315,220,70,25]);
    hmesh    = uicontrol('Style','pushbutton',...
                 'String','Mesh','Position',[315,180,70,25]);
    hcontour = uicontrol('Style','pushbutton',...
                 'String','Countour','Position',[315,135,70,25]);

    Each statement uses a series of uicontrol property/value pairs to define a push button:

    • The Style property specifies that the uicontrol is a push button.

    • The String property specifies the label on each push button: Surf, Mesh, and Contour.

    • The Position property specifies the location of each push button within the GUI and its size: [distance from left, distance from bottom, width, height]. Default units for push buttons are pixels.

    Each uicontrol call returns the handle of the push button created.

  2. Add the pop-up menu and its static text label to your GUI by adding these statements to the code file following the push button definitions. The first statement creates a popup menu and the second statement creates a text component that serves as a label for the popup menu.

    hpopup = uicontrol('Style','popupmenu',...
               'String',{'Peaks','Membrane','Sinc'},...
               'Position',[300,50,100,25]);
    htext  = uicontrol('Style','text','String','Select Data',...
               'Position',[325,90,60,15]);

    The pop-up menu component String property uses a cell array to specify the three items in the pop-up menu: Peaks, Membrane, and Sinc.

    The text component, the String property specifies instructions for the GUI user.

    For both components, the Position property specifies the location of each component within the GUI and its size: [distance from left, distance from bottom, width, height]. Default units for these components are pixels.

  3. Add the axes to the GUI by adding this statement to the code file.

    ha = axes('Units','pixels','Position',[50,60,200,185]);

    The Units property specifies pixels so that the axes has the same units as the other components.

  4. Following all the component definitions, add this line to the code file to align all components, except the axes, along their centers.

    align([hsurf,hmesh,hcontour,htext,hpopup],'Center','None');
  5. Add this command following the align command.

    %Make the GUI visible.
    set(f,'Visible','on')

    Your code file should look like this:

    function simple_gui2
    % SIMPLE_GUI2 Select a data set from the pop-up menu, then
    % click one of the plot-type push buttons. Clicking the button
    % plots the selected data in the axes.
    
       %  Create and then hide the GUI as it is being constructed.
       f = figure('Visible','off','Position',[360,500,450,285]);
       
       %  Construct the components.
       hsurf = uicontrol('Style','pushbutton','String','Surf',...
               'Position',[315,220,70,25]);
       hmesh = uicontrol('Style','pushbutton','String','Mesh',...
               'Position',[315,180,70,25]);
       hcontour = uicontrol('Style','pushbutton',...
               'String','Countour',...
               'Position',[315,135,70,25]); 
       htext = uicontrol('Style','text','String','Select Data',...
               'Position',[325,90,60,15]);
       hpopup = uicontrol('Style','popupmenu',...
               'String',{'Peaks','Membrane','Sinc'},...
               'Position',[300,50,100,25]);
       ha = axes('Units','Pixels','Position',[50,60,200,185]); 
       align([hsurf,hmesh,hcontour,htext,hpopup],'Center','None');
       
       %Make the GUI visible.
       set(f,'Visible','on')
    
    end
  6. Run your code by typing simple_gui2 at the command line. You can select a data set in the pop-up menu and click the push buttons, but nothing happens. This is because there is no callback code in the file to service the pop-up menu or the buttons.

Code the Simple Programmatic GUI

Program the Pop-Up Menu

The pop-up menu enables users to select the data to plot. When a GUI user selects one of the three data sets in the pop-up menu, MATLAB software sets the pop-up menu Value property to the index of the selected string. The pop-up menu callback reads the pop-up menu Value property to determine which item is currently displayed and sets current_data accordingly.

Add the following callback to your file following the initialization code and before the final end statement.

%  Pop-up menu callback. Read the pop-up menu Value property to
%  determine which item is currently displayed and make it the
%  current data. This callback automatically has access to 
%  current_data because this function is nested at a lower level.
   function popup_menu_Callback(source,eventdata) 
      % Determine the selected data set.
      str = get(source, 'String');
      val = get(source,'Value');
      % Set current data to the selected data set.
      switch str{val};
      case 'Peaks' % User selects Peaks.
         current_data = peaks_data;
      case 'Membrane' % User selects Membrane.
         current_data = membrane_data;
      case 'Sinc' % User selects Sinc.
         current_data = sinc_data;
      end
   end

Program the Push Buttons

Each of the three push buttons creates a different type of plot using the data specified by the current selection in the pop-up menu. The push button callbacks plot the data in current_data. They automatically have access to current_data because they are nested at a lower level.

Add the following callbacks to your file following the pop-up menu callback and before the final end statement.

% Push button callbacks. Each callback plots current_data in the
% specified plot type.

function surfbutton_Callback(source,eventdata) 
% Display surf plot of the currently selected data.
     surf(current_data);
end

function meshbutton_Callback(source,eventdata) 
% Display mesh plot of the currently selected data.
     mesh(current_data);
end

function contourbutton_Callback(source,eventdata) 
% Display contour plot of the currently selected data.
     contour(current_data);
end

Program the Callbacks

When the GUI user selects a data set from the pop-up menu or clicks one of the push buttons, MATLAB software executes the callback associated with that particular event. Use each component's Callback property to specify the name of the callback with which each event is associated.

  1. To the uicontrol statement that defines the Surf push button, add the property/value pair

    'Callback',{@surfbutton_Callback}

    so that the statement looks like this:

    hsurf = uicontrol('Style','pushbutton','String','Surf',...
            'Position',[315,220,70,25],...
            'Callback',{@surfbutton_Callback});

    Callback is the name of the property. surfbutton_Callback is the name of the callback that services the Surf push button.

  2. To the uicontrol statement that defines the Mesh push button, add the property/value pair

    'Callback',{@meshbutton_Callback}
  3. To the uicontrol statement that defines the Contour push button, add the property/value pair

    'Callback',{@contourbutton_Callback}
  4. To the uicontrol statement that defines the pop-up menu, add the property/value pair

    'Callback',{@popup_menu_Callback}

For more information, see Write Callbacks Using the Programmatic Workflow.

Initialize the Simple Programmatic GUI

Initialize the GUI, so it is ready for the user when the code makes the GUI visible. Make the GUI behave properly when it is resized by changing the component and figure units to normalized. This causes the components to resize when the GUI is resized. Normalized units map the lower-left corner of the figure window to (0,0) and the upper-right corner to (1.0, 1.0).

Replace this code in editor:

% Make the GUI visible.
set(f,'Visible','on')

with this code:

% Initialize the GUI.
% Change units to normalized so components resize automatically.
set([f,hsurf,hmesh,hcontour,htext,hpopup],'Units','normalized');

% Generate the data to plot.
peaks_data = peaks(35);
membrane_data = membrane;
[x,y] = meshgrid(-8:.5:8);
r = sqrt(x.^2+y.^2) + eps;
sinc_data = sin(r)./r;

% Create a plot in the axes.
current_data = peaks_data;
surf(current_data);

% Assign the GUI a name to appear in the window title.
set(f,'Name','Simple GUI')

% Move the GUI to the center of the screen.
movegui(f,'center')

% Make the GUI visible.
set(f,'Visible','on');

Verify Code and Run the Simple Programmatic GUI

Make sure your code appears as it should, and then run it.

  1. Verify that your code file looks like this:

    function simple_gui2
    % SIMPLE_GUI2 Select a data set from the pop-up menu, then
    % click one of the plot-type push buttons. Clicking the button
    % plots the selected data in the axes.
    
    %  Create and then hide the GUI as it is being constructed.
    f = figure('Visible','off','Position',[360,500,450,285]);
    
    % Construct the components.
    hsurf    = uicontrol('Style','pushbutton',...
                 'String','Surf','Position',[315,220,70,25],...
                 'Callback',{@surfbutton_Callback});
    hmesh    = uicontrol('Style','pushbutton',...
                 'String','Mesh','Position',[315,180,70,25],...
                 'Callback',{@meshbutton_Callback});
    hcontour = uicontrol('Style','pushbutton',...
                 'String','Countour','Position',[315,135,70,25],...
                 'Callback',{@contourbutton_Callback});
    htext  = uicontrol('Style','text','String','Select Data',...
               'Position',[325,90,60,15]);
    hpopup = uicontrol('Style','popupmenu',...
               'String',{'Peaks','Membrane','Sinc'},...
               'Position',[300,50,100,25],...
               'Callback',{@popup_menu_Callback});
    ha = axes('Units','pixels','Position',[50,60,200,185]);
    align([hsurf,hmesh,hcontour,htext,hpopup],'Center','None');
    
    % Initialize the GUI.
    % Change units to normalized so components resize automatically.
    set([f,hsurf,hmesh,hcontour,htext,hpopup],'Units','normalized');
    
    % Generate the data to plot.
    peaks_data = peaks(35);
    membrane_data = membrane;
    [x,y] = meshgrid(-8:.5:8);
    r = sqrt(x.^2+y.^2) + eps;
    sinc_data = sin(r)./r;
    
    % Create a plot in the axes.
    current_data = peaks_data;
    surf(current_data);
    
    % Assign the GUI a name to appear in the window title.
    set(f,'Name','Simple GUI')
    
    % Move the GUI to the center of the screen.
    movegui(f,'center')
    
    % Make the GUI visible.
    set(f,'Visible','on');
    
    %  Pop-up menu callback. Read the pop-up menu Value property to
    %  determine which item is currently displayed and make it the
    %  current data. This callback automatically has access to 
    %  current_data because this function is nested at a lower level.
       function popup_menu_Callback(source,eventdata) 
          % Determine the selected data set.
          str = get(source, 'String');
          val = get(source,'Value');
          % Set current data to the selected data set.
          switch str{val};
          case 'Peaks' % User selects Peaks.
             current_data = peaks_data;
          case 'Membrane' % User selects Membrane.
             current_data = membrane_data;
          case 'Sinc' % User selects Sinc.
             current_data = sinc_data;
          end
       end
    
      % Push button callbacks. Each callback plots current_data in the
      % specified plot type.
    
      function surfbutton_Callback(source,eventdata) 
      % Display surf plot of the currently selected data.
           surf(current_data);
      end
    
      function meshbutton_Callback(source,eventdata) 
      % Display mesh plot of the currently selected data.
           mesh(current_data);
      end
    
      function contourbutton_Callback(source,eventdata) 
      % Display contour plot of the currently selected data.
           contour(current_data);
      end
    end
  2. Run your code by typing simple_gui2 at the command line. The initialization code causes it to display the default peaks data with the surf function, making the GUI look like this.

  3. In the pop-up menu, select Membrane, and then click the Mesh button. The GUI displays a mesh plot of the

  4. Try other combinations before closing the GUI.

  5. Type help simple_gui2 at the command line. MATLAB software displays the help text.

    help simple_gui2
      SIMPLE_GUI2 Select a data set from the pop-up menu, then
      click one of the plot-type push buttons. Clicking the button
      plots the selected data in the axes.
Was this topic helpful?