BuildGui in Matlab
BuildGui in Matlab
App Building
R2018b
How to Contact MathWorks
Phone: 508-647-7000
v
A Simple Programmatic App
3
Create a Simple App Programmatically . . . . . . . . . . . . . . . 3-2
Create a Code File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Create the Figure Window . . . . . . . . . . . . . . . . . . . . . . . 3-3
Add Components to the UI . . . . . . . . . . . . . . . . . . . . . . . 3-4
Code the App’s Behavior . . . . . . . . . . . . . . . . . . . . . . . . . 3-7
Verify Code and Run the App . . . . . . . . . . . . . . . . . . . . 3-10
What Is GUIDE?
4
GUIDE: Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
UI Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
UI Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
vi Contents
Lay Out a UI Using GUIDE
6
GUIDE Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Access the Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Template Descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
vii
Programming a GUIDE App
7
Write Callbacks in GUIDE . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
Callbacks for Different User Actions . . . . . . . . . . . . . . . . 7-2
GUIDE-Generated Callback Functions and Property
Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4
GUIDE Callback Syntax . . . . . . . . . . . . . . . . . . . . . . . . . 7-5
Renaming and Removing GUIDE-Generated Callbacks . . 7-6
viii Contents
GUIDE App With Parameters for Displaying Plots . . . . . . 8-7
Open and Run the Example . . . . . . . . . . . . . . . . . . . . . . . 8-7
Examine the Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-8
ix
Lay Out a UI Programmatically . . . . . . . . . . . . . . . . . . . . 9-25
Component Placement and Sizing . . . . . . . . . . . . . . . . . 9-25
Managing the Layout in Resizable UIs . . . . . . . . . . . . . 9-30
Manage the Stacking Order of Grouped Components . . 9-33
x Contents
Manage Application-Defined Data
11
Share Data Among Callbacks . . . . . . . . . . . . . . . . . . . . . . 11-2
Overview of Data Sharing Techniques . . . . . . . . . . . . . . 11-2
Store Data in UserData or Other Object Properties . . . . 11-3
Store Data as Application Data . . . . . . . . . . . . . . . . . . . 11-8
Create Nested Callback Functions (Programmatic
Apps) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-12
Store Data Using the guidata Function . . . . . . . . . . . . 11-13
GUIDE Example: Share Slider Data Using guidata . . . 11-16
GUIDE Example: Share Data Between Two Apps . . . . 11-16
GUIDE Example: Share Data Among Three Apps . . . . 11-17
xi
App Designer
xii Contents
Datetime Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-18
Duration Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-19
Nonscalar Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-20
Missing Data Values . . . . . . . . . . . . . . . . . . . . . . . . . . 15-21
Example: App that Displays a Table Array . . . . . . . . . . 15-22
App Layout
16
Lay Out Apps in App Designer . . . . . . . . . . . . . . . . . . . . . 16-2
Customizing Components . . . . . . . . . . . . . . . . . . . . . . . 16-3
Aligning and Spacing Components . . . . . . . . . . . . . . . . 16-4
Grouping Components . . . . . . . . . . . . . . . . . . . . . . . . . 16-6
Arranging Components in Containers . . . . . . . . . . . . . . 16-7
App Programming
17
Managing Code in App Designer Code View . . . . . . . . . . 17-2
Managing Components, Functions, and Properties . . . . 17-2
Identifying Editable Sections of Code . . . . . . . . . . . . . . 17-3
Programming Your App . . . . . . . . . . . . . . . . . . . . . . . . . 17-4
Fixing Coding Problems and Run-Time Errors . . . . . . . . 17-7
xiii
Startup Tasks and Input Arguments in App Designer . . 17-8
Create a StartupFcn Callback . . . . . . . . . . . . . . . . . . . . 17-8
Define Input App Arguments . . . . . . . . . . . . . . . . . . . . . 17-9
xiv Contents
App Designer Examples
18
Mortgage Calculator App in App Designer . . . . . . . . . . . 18-2
Keyboard Shortcuts
19
App Designer Keyboard Shortcuts . . . . . . . . . . . . . . . . . . 19-2
Shortcuts Available Throughout App Designer . . . . . . . 19-2
Component Browser Shortcuts . . . . . . . . . . . . . . . . . . . 19-2
Design View Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . 19-3
Code View Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . 19-8
xv
App Packaging
xvi Contents
Introduction to Creating UIs
17
1
Each of these approaches offers a different workflow and a slightly different set of
functionality. The best choice for you depends on your project requirements and how you
prefer to work.
1-2
Ways to Build Apps
Use GUIDE
GUIDE is a drag-and-drop environment for laying out user interfaces (UIs). You code the
interactive behavior of your app separately, in the MATLAB editor. Apps created with
GUIDE are compatible with almost all other releases, and they support all the graphics
functionality in MATLAB.
1-3
1 About Apps in MATLAB Software
1-4
Ways to Build Apps
1-5
1 About Apps in MATLAB Software
See Also
Related Examples
• “App Designer Versus GUIDE” on page 14-6
• “Create a Simple App Using GUIDE” on page 2-2
• “Create a Simple App Programmatically” on page 3-2
• “Create and Run a Simple App Using App Designer” on page 14-2
• “Displaying Graphics in App Designer” on page 14-9
1-6
2
Note This topic applies to apps you create using GUIDE. For alternative ways to build
apps, see “Ways to Build Apps” on page 1-2.
This example shows how to use GUIDE to create an app that has a simple user interface
(UI), such as the one shown here.
Subsequent sections guide you through the process of creating this app.
If you only want to view and run the code that created this app, 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_gui*.*')),fileattrib('simple_gui*.*', '+w');
guide simple_gui.fig;
edit simple_gui.m
2-2
Create a Simple App Using GUIDE
2 In the GUIDE Quick Start dialog box, select the Blank GUI (Default) template, and
then click OK.
2-3
2 How to Create a App with GUIDE
2-4
Create a Simple App Using GUIDE
2-5
2 How to Create a App with GUIDE
Layout the UI
Add, align, and label the components in the UI.
1 Add the three push buttons to the UI. Select the push button tool from the component
palette at the left side of the Layout Editor and drag it into the layout area. Create
three buttons, positioning them approximately as shown in the following figure.
2-6
Create a Simple App Using GUIDE
Arrange the components as shown in the following figure. Resize the axes component
to approximately 2-by-2 inches.
2-7
2 How to Create a App with GUIDE
If several components have the same parent, you can use the Alignment Tool to align
them to one another. To align the three push buttons:
1 Select all three push buttons by pressing Ctrl and clicking them.
2 Select Tools > Align Objects.
3 Make these settings in the Alignment Tool:
2-8
Create a Simple App Using GUIDE
4 Click OK.
2-9
2 How to Create a App with GUIDE
Each of the three push buttons specifies a plot type: surf, mesh, and contour. This section
shows you how to label the buttons with those options.
2-10
Create a Simple App Using GUIDE
3 In the Property Inspector, select the String property, and then replace the existing
value with the word Surf.
4 Press the Enter key. The push button label changes to Surf.
2-11
2 How to Create a App with GUIDE
5 Click each of the remaining push buttons in turn and repeat steps 3 and 4. Label the
middle push button Mesh, and the bottom button Contour.
The pop-up menu provides a choice of three data sets: peaks, membrane, and sinc. These
data sets correspond to MATLAB functions of the same name. This section shows you how
to list those data sets as choices in the pop-menu.
2-12
Create a Simple App Using GUIDE
3 Replace the existing text with the names of the three data sets: peaks, membrane,
and sinc. Press Enter to move to the next line.
The first item in your list, peaks, appears in the pop-up menu in the layout area.
In this UI, the static text serves as a label for the pop-up menu. This section shows you
how to change the static text to read Select Data.
2-13
2 How to Create a App with GUIDE
3 Click OK.
The phrase Select Data appears in the static text component above the pop-up
menu.
When you save a layout, GUIDE creates two files, a FIG-file and a code file. The FIG-file,
with extension .fig, is a binary file that contains a description of the layout. The code
file, with extension .m, contains MATLAB functions that control the app’s behavior.
1 Save and run your program by selecting Tools > Run.
2 GUIDE displays a dialog box displaying: “Activating will save changes to your figure
file and MATLAB code. Do you wish to continue?
Click Yes.
2-14
Create a Simple App Using GUIDE
3 GUIDE opens a Save As dialog box in your current folder and prompts you for a FIG-
file name.
4 Browse to any folder for which you have write privileges, and then enter the file
name simple_gui for the FIG-file. GUIDE saves both the FIG-file and the code file
using this name.
5 If the folder in which you save the files is not on the MATLAB path, GUIDE opens a
dialog box that allows you to change the current folder.
6 GUIDE saves the files simple_gui.fig and simple_gui.m, and then runs the
program. It also opens the code file in your default editor.
The app opens in a new window. Notice that the window lacks the standard menu bar
and toolbar that MATLAB figure windows display. You can add your own menus and
toolbar buttons with GUIDE, but by default a GUIDE app includes none of these
components.
When you run simple_gui, you can select a data set in the pop-up menu and click
the push buttons, but nothing happens. This is because the code file contains no
statements to service the pop-up menu and the buttons.
2-15
2 How to Create a App with GUIDE
To run an app created with GUIDE without opening GUIDE, execute its code file by typing
its name.
simple_gui
You can also use the run command with the code file, for example,
run simple_gui
Note Do not attempt to run your app by opening its FIG-file outside of GUIDE. If you do
so, the figure opens and appears ready to use, but the UI does not initialize and the
callbacks do not function.
This section shows you how to generate the data to be plotted when the user clicks a
button. The opening function generates this data by calling MATLAB functions. The
opening function initializes the UI when it opens, and it is the first callback in every
GUIDE-generated code file.
In this example, you add code that creates three data sets to the opening function. The
code uses the MATLAB functions peaks, membrane, and sinc.
1 Display the opening function in the MATLAB Editor.
If the file simple_gui.m is not already open in the editor, open from the Layout
Editor by selecting View > Editor.
2 On the EDITOR tab, in the NAVIGATE section, click Go To, and then select
simple_gui_OpeningFcn.
The cursor moves to the opening function, which contains this code:
% --- Executes just before simple_gis made visible.
function simple_gui_OpeningFcn(hObject, eventdata, handles, varargin)
2-16
Create a Simple App Using GUIDE
The first six executable lines create the data using the MATLAB functions peaks,
membrane, and sinc. They store the data in the handles structure, an argument
provided to all callbacks. Callbacks for the push buttons can retrieve the data from
the handles structure.
The last two lines create a current data value and set it to peaks, and then display the
surf plot for peaks. The following figure shows how the app looks when it first
displays.
2-17
2 How to Create a App with GUIDE
The pop-up menu presents options for plotting the data. When the user selects one of the
three plots, MATLAB software sets the pop-up menu Value property to the index of the
selected menu item. The pop-up menu callback reads the pop-up menu Value property to
determine the item that the menu currently displays, and sets handles.current_data
accordingly.
1 Display the pop-up menu callback in the MATLAB Editor. In the GUIDE Layout Editor,
right-click the pop-up menu component, and then select View Callbacks >
Callback.
2-18
Create a Simple App Using GUIDE
GUIDE displays the code file in the Editor, and moves the cursor to the pop-menu
callback, which contains this code:
% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
2 Add the following code to the popupmenu1_Callback after the comment that begins
% handles...
2-19
2 How to Create a App with GUIDE
• Value — the index into the menu contents of the selected data set
The code then uses a switch statement to make the selected data set the current
data. The last statement saves the changes to the handles structure.
Each of the 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 get data from the
handles structure and then plot it.
1 Display the Surf push button callback in the MATLAB Editor. In the Layout Editor,
right-click the Surf push button, and then select View Callbacks > Callback.
2-20
Create a Simple App Using GUIDE
In the Editor, the cursor moves to the Surf push button callback in the code file,
which contains this code:
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
2 Add the following code to the callback immediately after the comment that begins %
handles...
2-21
2 How to Create a App with GUIDE
1 Run your program from the Layout Editor by selecting Tools > Run.
2 In the pop-up menu, select Membrane, and then click the Mesh button. The app
displays a mesh plot of the MathWorks® L-shaped Membrane logo.
3 Try other combinations before closing the window.
2-22
See Also
See Also
Related Examples
• “Ways to Build Apps” on page 1-2
• “Create a Simple App Programmatically” on page 3-2
• “Create and Run a Simple App Using App Designer” on page 14-2
2-23
2 How to Create a App with GUIDE
• A FIG-file, with extension .fig, that contains a complete description of the layout and
each component, such as push buttons, axes, panels, menus, and so on. The FIG-file is
a binary file and you cannot modify it except by changing the layout in GUIDE. FIG-
files are specializations of MAT-files. See “Custom Applications to Access MAT-Files”
for more information.
• A code file, with extension .m, that initially contains initialization code and templates
for some callbacks that control behavior. You generally add callbacks you write for
your components to this file. As the callbacks are functions, the code file can never be
a MATLAB script.
When you save your app for the first time, GUIDE automatically opens the code file in
your default editor.
The FIG-file and the code file must have the same name. These two files usually reside in
the same folder, and correspond to the tasks of laying out and programming the app.
When you lay out the app in the Layout Editor, your components and layout is stored in
the FIG-file. When you program the app, your code is stored in the corresponding code
file.
If your app includes ActiveX® components, GUIDE also generates a file for each ActiveX
component.
2-24
Files Generated by GUIDE
then the name of the main function is mygui. Each callback in the file is a local function
of that main function.
When GUIDE generates a code file, it automatically includes templates for the most
commonly used callbacks for each component. The code file also contains initialization
code, as well as an opening function callback and an output function callback. It is your
job to add code to the component callbacks for your app to work as you want. You can
also add code to the opening function callback and the output function callback. The code
file orders functions as shown in the following table.
Section Description
Comments Displayed at the command line in response to the help
command.
Initialization GUIDE initialization tasks. Do not edit this code.
Opening function Performs your initialization tasks before the user has access to
the UI.
Output function Returns outputs to the MATLAB command line after the opening
function returns control and before control returns to the
command line.
Component and figure Control the behavior of the window and of individual
callbacks components. MATLAB software calls a callback in response to a
particular event for a component or for the figure itself.
Utility/helper functions Perform miscellaneous functions not directly associated with an
event for the figure or a component.
Within GUIDE, you can add a local callback function template to the code in any of the
following ways. Select the component for which you want to add the callback, and then:
• Right-click the mouse button, and from the View callbacks submenu, select the
desired callback.
• From View > View Callbacks, select the desired callback.
2-25
2 How to Create a App with GUIDE
Property Inspector, click the pencil-and-paper icon next to the name of the
callback you want to install in the code file.
• For toolbar buttons, in the Toolbar Editor, click the View button next to Clicked
Callback (for Push Tool buttons) or On Callback, or Off Callback (for Toggle Tools).
When you perform any of these actions, GUIDE adds the callback template to the code
file, saves it, and opens it for editing at the callback you just added. If you select a
callback that currently exists in the code file, GUIDE adds no callback, but saves the file
and opens it for editing at the callback you select.
For more information, see “GUIDE-Generated Callback Functions and Property Values” on
page 7-4.
GUIDE names callbacks based on the callback type and the component Tag property.
For example, togglebutton1_Callback is such a default callback name. If you
change a component Tag, GUIDE renames all its callbacks in the code file to contain
the new tag. You can change the name of a callback, replace it with another function,
or remove it entirely using the Property Inspector.
• GUIDE provides three arguments on page 7-5 to callbacks, always named the same.
• You can append arguments to GUIDE-generated callbacks, but never alter or remove
the ones that GUIDE places there.
• You can rename a GUIDE-generated callback by editing its name or by changing the
component Tag.
• You can delete a callback from a component by clearing it from the Property Inspector;
this action does not remove anything from the code file.
• You can specify the same callback function for multiple components to enable them to
share code.
After you delete a component in GUIDE, all callbacks it had remain in the code file. If you
are sure that no other component uses the callbacks, you can then remove the callback
2-26
See Also
code manually. For details, see “Renaming and Removing GUIDE-Generated Callbacks” on
page 7-6.
See Also
Related Examples
• “Create a Simple App Using GUIDE” on page 2-2
• “Write Callbacks in GUIDE” on page 7-2
2-27
3
Note This topic applies to apps you create programmatically using the figure function.
For alternative ways to build apps, see “Ways to Build Apps” on page 1-2.
This example shows how to create a simple app programmatically, such as the one shown
here.
Subsequent sections guide you through the process of creating this app.
If you prefer to view and run the code that created this app 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
3-2
Create a Simple App Programmatically
Note This code uses dot notation to set graphics object properties. Dot notation runs in
R2014b and later. If you are using an earlier release, use the set function instead. For
example, change f.Visible = 'on' to set(f,'Visible','on').
To run the code, go to the Run section in the Editor tab. Then click Run .
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.)
The call to the figure function creates a traditional figure and sets the following
properties:
3-3
3 A Simple Programmatic App
• The Visible property is set to 'off' to make the window invisible as components
are added or initialized. The window becomes visible when the UI has all its
components and is initialized.
• The Position property is set to a four-element vector that specifies the location of
the UI on the screen and its size: [distance from left, distance from bottom, width,
height]. Default units are pixels.
1 Following the call to figure, add these statements to your code file to create three
push button components.
Each uicontrol call returns the handle of the push button created.
2 Add the pop-up menu and a text label by adding these statements to the code file
following the push button definitions. The first statement creates the label. The
second statement creates the popup menu.
3-4
Create a Simple App Programmatically
'String',{'Peaks','Membrane','Sinc'},...
'Position',[300,50,100,25]);
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 user.
For both components, the Position property specifies the size and location of each
component: [distance from left, distance from bottom, width, height]. Default units
for these components are pixels.
3 Add the axes 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.
Note This code uses dot notation to set object properties. Dot notation runs in
R2014b and later. If you are using an earlier release, use the set function instead.
For example, change f.Visible = 'on' to set(f,'Visible','on').
f.Visible = 'on';
3-5
3 A Simple Programmatic App
'Position',[315,220,70,25]);
hmesh = uicontrol('Style','pushbutton','String','Mesh',...
'Position',[315,180,70,25]);
hcontour = uicontrol('Style','pushbutton',...
'String','Contour',...
'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');
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.
3-6
Create a Simple App Programmatically
The pop-up menu enables users to select the data to plot. When a 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 menu item. 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.
Note This code uses dot notation to get object properties. Dot notation runs in R2014b
and later. If you are using an earlier release, use the get function instead. For example,
change str = source.String to str = get(source,'String').
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.
3-7
3 A Simple Programmatic App
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
When the 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}
3-8
Create a Simple App Programmatically
'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 for Apps Created Programmatically” on page
10-5.
Initialize the UI
Initialize the UI, so it is ready when the window becomes visible. Make the UI behave
properly when it is resized by changing the component and figure units to normalized.
This causes the components to resize when the UI 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).
Note This code uses dot notation to set object properties. Dot notation runs in R2014b
and later. If you are using an earlier release, use the set function instead. For example,
change f.Units = 'normalized' to set(f,'Units','normalized').
3-9
3 A Simple Programmatic App
r = sqrt(x.^2+y.^2) + eps;
sinc_data = sin(r)./r;
Note This code uses dot notation to get and set object properties. Dot notation runs in
R2014b and later. If you are using an earlier release, use the get and set functions
instead. For example, change f.Units = 'normalized' to
set(f,'Units','normalized').
3-10
Create a Simple App Programmatically
hcontour = uicontrol('Style','pushbutton',...
'String','Contour','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');
3-11
3 A Simple Programmatic App
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 app 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 UI
look like this.
3-12
See Also
3 In the pop-up menu, select Membrane, and then click the Mesh button. The UI
displays a mesh plot of the MathWorks L-shaped Membrane logo.
4 Try other combinations before closing the UI.
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.
See Also
Related Examples
• “Ways to Build Apps” on page 1-2
• “Create a Simple App Using GUIDE” on page 2-2
• “Create and Run a Simple App Using App Designer” on page 14-2
3-13
Create UIs with GUIDE
15
4
What Is GUIDE?
4 What Is GUIDE?
UI Layout
GUIDE is a development environment that provides a set of tools for creating user
interfaces (UIs). These tools simplify the process of laying out and programming UIs.
Using the GUIDE Layout Editor, you can populate a UI by clicking and dragging UI
components—such as axes, panels, buttons, text fields, sliders, and so on—into the layout
area. You also can create menus and context menus for the UI. From the Layout Editor,
you can size the UI, modify component look and feel, align components, set tab order,
view a hierarchical list of the component objects, and set UI options.
UI Programming
GUIDE automatically generates a program file containing MATLAB functions that controls
how the UI behaves. This code file provides code to initialize the UI, and it contains a
framework for the UI callbacks. Callbacks are functions that execute when the user
interacts with a UI component. Use the MATLAB Editor to add code to these callbacks.
Note MATLAB software provides a selection of standard dialog boxes that you can create
with a single function call. For an example, see the documentation for msgbox, which also
provides links to functions that create specialized predefined dialog boxes.
4-2
5
GUIDE Preferences
In this section...
“Set Preferences” on page 5-2
“Confirmation Preferences” on page 5-2
“Backward Compatibility Preference” on page 5-4
“All Other Preferences” on page 5-4
Set Preferences
You can set preferences for GUIDE. From the MATLAB Home tab, in the Environment
section, click Preferences. These preferences apply to GUIDE and to all UIs you create.
The preferences are in different locations within the Preferences dialog box:
Confirmation Preferences
GUIDE provides two confirmation preferences. You can choose whether you want to
display a confirmation dialog box when you
In the Preferences dialog box, click MATLAB > General > Confirmation Dialogs to
access the GUIDE confirmation preferences. Look for the word GUIDE in the Tool column.
5-2
GUIDE Preferences
When you activate a UI from the Layout Editor by clicking the Run button , a dialog box
informs you of the impending save and lets you choose whether or not you want to
continue.
5-3
5 GUIDE Preferences and Options
From the Layout Editor, when you select File > Export, a dialog box informs you of the
impending save and lets you choose whether or not you want to continue.
UI FIG-files created or modified with MATLAB 7.0 or a later version are not automatically
compatible with Version 6.5 and earlier versions. GUIDE automatically generates FIG-
files, which are binary files that contain the UI layout information.
To make a FIG-file backward compatible, from the Layout Editor, select File >
Preferences > General > MAT-Files, and then select MATLAB Version 5 or later
(save -v6).
Note The -v6 option discussed in this section is obsolete and will be removed in a future
version of MATLAB.
5-4
GUIDE Preferences
Displays both icons and names in the component palette, as shown below. When
unchecked, the icons alone are displayed in two columns, with tooltips.
5-5
5 GUIDE Preferences and Options
Displays the FIG-file file name with its file extension, .fig, in the Layout Editor window
title. If unchecked, only the file name is displayed.
Displays the full file path in the Layout Editor window title. If unchecked, the file path is
not displayed.
Callbacks are blocks of code that execute in response to actions by the user, such as
clicking buttons or manipulating sliders. By default, GUIDE sets up templates that declare
callbacks as functions and adds comments at the beginning of each one. Most of the
comments are similar to the following.
5-6
See Also
Some callbacks are added automatically because their associated components are part of
the original GUIDE template that you chose. Other commonly used callbacks are added
automatically when you add components. You can also add callbacks explicitly by
selecting them from View > View Callbacks menu or on the component's context menu.
If you deselect this preference, GUIDE includes comments only for callbacks that are
automatically included to support the original GUIDE template. GUIDE does not include
comments for callbacks subsequently added to the code.
See “Write Callbacks in GUIDE” on page 7-2 for more information about callbacks and
about the arguments described in the preceding comments.
See Also
Related Examples
• “GUIDE Options” on page 5-8
5-7
5 GUIDE Preferences and Options
GUIDE Options
In this section...
“The GUI Options Dialog Box” on page 5-8
“Resize Behavior” on page 5-9
“Command-Line Accessibility” on page 5-9
“Generate FIG-File and MATLAB File” on page 5-10
“Generate FIG-File Only” on page 5-12
5-8
GUIDE Options
Resize Behavior
You can control whether users can resize the window and how MATLAB handles resizing.
GUIDE provides three options:
The first two options set figure and component properties appropriately and require no
other action. Other (Use SizeChangedFcn) requires you to write a callback routine that
recalculates sizes and positions of the components based on the new figure size.
Command-Line Accessibility
You can restrict access to a figure window from the command line or from a code file with
the GUIDE Command-line accessibility options.
Unless you explicitly specify a figure handle, many commands, such as plot, alter the
current figure (the figure specified by the root CurrentFigure property and returned by
the gcf command). The current figure is usually the figure that is most recently created,
drawn into, or mouse-clicked. You can programmatically designate a figure h (where h is
its handle) as the current figure in four ways:
h = gcf
5-9
5 GUIDE Preferences and Options
For a UI created in GUIDE, set the Command-line accessibility option to prevent users
from inadvertently changing the appearance or content of a UI by executing commands at
the command line or from a script or function, such as plot. The following table briefly
describes the four options for Command-line accessibility.
Option Description
Callback (GUI becomes Current Figure The UI can be accessed only from within a
within Callbacks) callback. The UI cannot be accessed from
the command line or from a script. This is
the default.
Off (GUI never becomes Current The UI cannot be accessed from a callback,
Figure) the command line, or a script, without the
handle.
On (GUI may become Current Figure The UI can be accessed from a callback,
from Command Line) from the command line, and from a script.
Other (Use settings from Property You control accessibility by setting the
Inspector) HandleVisibility and IntegerHandle
properties from the Property Inspector.
See “Files Generated by GUIDE” on page 2-24 for information about these files.
If you select Generate callback function prototypes in the GUI Options dialog,
GUIDE adds templates for the most commonly used callbacks to the code file for most
components. You must then insert code into these templates.
5-10
GUIDE Options
GUIDE also adds a callback whenever you edit a callback routine from the Layout Editor's
right-click context menu and when you add menus to the UI using the Menu Editor on
page 6-78.
See “Write Callbacks in GUIDE” on page 7-2 for general information about callbacks.
Note This option is available only if you first select the Generate FIG-file and MATLAB
file option.
This option allows you to select between two behaviors for the figure window:
If you allow only one instance, the software reuses the existing figure whenever the
command to run your program is executed. If a UI window already exists, the software
brings it to the foreground rather than creating a new figure.
If you clear this option, the software creates a new figure whenever you issue the
command to run the program.
Even if you allow only one instance of a UI to exist, initialization can take place each time
you invoke it from the command line. For example, the code in an OpeningFcn will run
each time a GUIDE program runs unless you take steps to prevent it from doing so.
Adding a flag to the handles structure is one way to control such behavior. You can do
this in the OpeningFcn, which can run initialization code if this flag doesn't yet exist and
skip that code if it does.
Note This option is available only if you first select the Generate FIG-file and MATLAB
file option.
The default color used for UI components is system dependent. This option enables you to
make the figure background color the same as the default component background color.
5-11
5 GUIDE Preferences and Options
To ensure that the figure background matches the color of the components, select Use
system color scheme for background in the GUI Options dialog.
Note This option is available only if you first select the Generate FIG-file and MATLAB
file option.
GUIDE selects Generate FIG-file only as the default if you do one of the following:
• Start GUIDE from the command line by providing one or more figure objects as
arguments.
guide(f)
In this case, GUIDE selects Generate FIG-file only, even when a code file with a
corresponding name exists in the same folder.
• Start GUIDE from the command line and provide the name of a FIG-file for which no
code file with the same name exists in the same folder.
guide('myfig.fig')
• Use the GUIDE Open Existing GUI tab to open a FIG-file for which no code file with
the same name exists in the same folder.
When you save the figure or UI with Generate FIG-file only selected, GUIDE saves only
the FIG-file. You must update any corresponding code files yourself, as appropriate.
If you want GUIDE to manage the UI code file for you, change the selection to Generate
FIG-file and MATLAB file before saving the UI. If there is no corresponding code file in
the same location, GUIDE creates one. If a code file with the same name as the original
figure or UI exists in the same folder, GUIDE overwrites it. To prevent overwriting an
existing file, save the UI using Save As from the File menu. Select another file name for
the two files. GUIDE updates variable names in the new code file as appropriate.
5-12
See Also
Even when there is no code file associated with a UI FIG-file, you can still provide
callbacks for UI components to make them perform actions when used. In the Property
Inspector, you can type callbacks in the form of character vectors, built-in functions, or
MATLAB code file names; when your program runs, it will execute them if possible. If the
callback is a file name, it can include arguments to that function. For example, setting the
Callback property of a push button to sqrt(2) causes the result of the expression to
display in the Command Window:
ans =
1.4142
Any file that a callback executes must be in the current folder or on the MATLAB path.
For more information on how callbacks work, see “Write Callbacks in GUIDE” on page 7-
2
See Also
Related Examples
• “GUIDE Preferences” on page 5-2
5-13
6
GUIDE Templates
In this section...
“Access the Templates” on page 6-2
“Template Descriptions” on page 6-3
To use a template:
1 Select a template in the left pane. A preview displays in the right pane.
2 Optionally, name your UI now by selecting Save new figure as and typing the name
in the field to the right. GUIDE saves the UI before opening it in the Layout Editor. If
you choose not to name the UI at this point, GUIDE prompts you to save it and give it
a name the first time you run your program.
6-2
GUIDE Templates
Template Descriptions
GUIDE provides four fully functional templates. They are described in the following
sections:
“Out of the box,” none of the UI templates include a menu bar or a toolbar. Neither can
they dock in the MATLAB desktop. You can, however, override these GUIDE defaults to
provide and customize these controls. See the sections “Create Menus for GUIDE Apps”
on page 6-78 and “Create Toolbars for GUIDE UIs” on page 6-95 for details.
Note To see how the templates work, you can view their code and look at their callbacks.
You can also modify the callbacks for your own purposes. To view the code file for any of
these templates, open the template in the Layout Editor and click the Editor button on
the toolbar.
Blank GUI
6-3
6 Lay Out a UI Using GUIDE
Select this template when the other templates are not suitable for the UI you want to
create.
The following figure shows an example of this template. The user interface controls
shown in this template are the push buttons, radio buttons, edit text, and static text.
6-4
GUIDE Templates
When you click the Run button , the UI appears as shown in the following figure.
6-5
6 Lay Out a UI Using GUIDE
When you enter values for the density and volume of an object, and click the Calculate
button, the program calculates the mass of the object and displays the result next to
Mass(D*V).
To view the code for these user interface controls, open the template in the Layout Editor
and click the Editor button on the toolbar.
6-6
GUIDE Templates
When you click the Run button on the toolbar, the UI displays a plot of five lines, each
of which is generated from random numbers using the MATLAB rand(5) command. The
following figure shows an example.
6-7
6 Lay Out a UI Using GUIDE
You can select other plots in the pop-up menu. Clicking the Update button displays the
currently selected plot on the axes.
• Open displays a dialog box from which you can open files on your computer.
• Print opens the Print dialog box. Clicking OK in the Print dialog box prints the figure.
• Close closes the UI.
To view the code for these menu choices, open the template in the Layout Editor and click
the Editor button on the toolbar.
6-8
GUIDE Templates
When you click the Run button, the following dialog displays.
6-9
6 Lay Out a UI Using GUIDE
The dialog box returns Yes or No, depending on which button you click.
Select this template if you want the dialog box to return the user’s selection, or if you
want to create a modal dialog box.
Modal dialog boxes are blocking, which means that the code stops executing while dialog
exists. This means that the user cannot interact with other MATLAB windows until they
click one of the dialog buttons.
To view the code for this dialog, open the template in the Layout Editor and click the
Editor button on the toolbar.
See Also
Related Examples
• “Ways to Build Apps” on page 1-2
• “Create a Simple App Using GUIDE” on page 2-2
• “Add Components to the GUIDE Layout Area” on page 6-13
6-10
Set the UI Window Size in GUIDE
As you drag the corner handle, the readout in the lower right corner shows the current
position of the UI in pixels.
1 Set each object’s Units property to an absolute value, such as inches or pixels
before enlarging the UI.
To change the Units property for all the objects in your UI simultaneously, drag a
selection box around all the objects, and then click the Property Inspector button
and set the Units.
2 When you finish enlarging the UI, set each object’s Units property back to
normalized.
6-11
6 Lay Out a UI Using GUIDE
See Also
Related Examples
• “Ways to Build Apps” on page 1-2
• “Create a Simple App Using GUIDE” on page 2-2
• “GUIDE Options” on page 5-8
6-12
Add Components to the GUIDE Layout Area
Place Components
The component palette at the left side of the Layout Editor contains the components that
you can add to your UI.
Note See “Create Menus for GUIDE Apps” on page 6-78 for information about adding
menus to a UI. See “Create Toolbars for GUIDE UIs” on page 6-95 for information about
working with the toolbar.
To place components in the GUIDE layout area and give each component a unique
identifier, follow these steps:
• Drag a component from the palette and drop it in the layout area.
• Click a component in the palette and move the cursor over the layout area. The
cursor changes to a cross. Click again to add the component in its default size, or
click and drag to size the component as you add it.
6-13
6 Lay Out a UI Using GUIDE
Once you have defined a UI component in the layout area, selecting it automatically
shows it in the Property Inspector. If the Property Inspector is not open or is not
visible, double-clicking a component raises the inspector and focuses it on that
component.
The components listed in the following table have additional considerations; read
more about them in the sections described there.
See “Grid and Rulers” on page 6-72 for information about using the grid.
3 Assign a unique identifier to each component. Do this by setting the value of the
component Tag properties. See“Assign an Identifier to Each Component” on page 6-
19 for more information.
4 Specify the look and feel of each component by setting the appropriate properties.
The following topics contain specific information.
This is an example of a UI in the Layout Editor. Components in the Layout Editor are not
active.
6-14
Add Components to the GUIDE Layout Area
The status bar at the bottom of the GUIDE Layout Editor displays:
• Current Point — The current location of the mouse relative to the lower left corner of
the grid area in the Layout Editor.
• Position — The Position property of the selected component is a vector: [distance
from left, distance from bottom, width, height], where distances are relative to the
parent figure, panel, or button group.
Here is how to interpret the coordinates in the status bar and rulers:
6-15
6 Lay Out a UI Using GUIDE
• The Position values updates as you move and resize components. The first two
elements in the vector change as you move the component. The last two elements of
the vector change as the height and width of the component change.
• When no components are selected, the Position value displays the location and size of
the figure.
To add a component to a panel or button group, select the component in the component
palette then move the cursor over the desired panel or button group. The position of the
cursor determines the component's parent.
GUIDE highlights the potential parent as shown in the following figure. The highlight
indicates that if you drop the component or click the cursor, the component will be a child
of the highlighted panel, button group, or figure.
6-16
Add Components to the GUIDE Layout Area
Note Assign a unique identifier to each component in your panel or button group by
setting the value of its Tag property. See “Assign an Identifier to Each Component” on
page 6-19 for more information.
6-17
6 Lay Out a UI Using GUIDE
When you add a new component or drag an existing component to a panel or button
group, it will become a member, or child, of the panel or button group automatically,
whether fully or partially enclosed by it. However, if the component is not entirely
contained in the panel or button group, it appears to be clipped in the Layout Editor and
in the running app.
You can add a new panel or button group to a UI in order to group any of its existing
controls. In order to include such controls in a new panel or button group, do the
following. The instructions refer to panels, but you do the same for components inside
button groups.
1 Select the New Panel or New Button Group tool and drag out a rectangle to have the
size and position you want.
The panel will not obscure any controls within its boundary unless they are axes,
tables, or other panels or button groups. Only overlap panels you want to nest, and
then make sure the overlap is complete.
2 You can use Send Backward or Send to Back on the Layout menu to layer the new
panel behind components you do not want it to obscure, if your layout has this
problem. As you add components to it or drag components into it, the panel will
automatically layer itself behind them.
Now is a good time to set the panel's Tag and String properties to whatever you
want them to be, using the Property Inspector.
3 Open the Object Browser from the View menu and find the panel you just added. Use
this tool to verify that it contains all the controls you intend it to group together. If
any are missing, perform the following steps.
4 Drag controls that you want to include but don't fit within the panel inside it to
positions you want them to have. Also, slightly move controls that are already in their
correct positions to group them with the panel.
The panel highlights when you move a control, indicating it now contains the control.
The Object Browser updates to confirm the relationship. If you now move the panel,
its child controls move with it.
Tip You need to move controls with the mouse to register them with the surrounding
panel or button group, even if only by a pixel or two. Selecting them and using arrow
6-18
Add Components to the GUIDE Layout Area
keys to move them does not accomplish this. Use the Object Browser to verify that
controls are properly nested.
See “Panels and Button Groups” on page 6-40 for more information on how to
incorporate panels and button groups into a UI.
Use the Tag property to assign a unique and meaningful identifier to your components.
When you place a component in the layout area, GUIDE assigns a default value to the Tag
property. Before saving the UI, replace this value with a name or abbreviation that
reflects the role of the component in the UI.
The name you assign is used by code to identify the component and must be unique in the
UI. To set the Tag property:
1 Select View > Property Inspector or click the Property Inspector button .
2 In the layout area, select the component for which you want to set Tag.
3 In the Property Inspector, select Tag and then replace the value with the name you
want to use as the identifier. In the following figure, Tag is set to pushbutton1.
To define user interface controls, you must set certain properties. To do this:
6-19
6 Lay Out a UI Using GUIDE
1 Use the Property Inspector to modify the appropriate properties. Open the Property
Inspector by selecting View > Property Inspector or by clicking the Property
Inspector button .
2 In the layout area, select the component you are defining.
Subsequent topics describe commonly used properties of user interface controls and offer
a simple example for each kind of control:
The most commonly used properties needed to describe a user interface control are
shown in the following table. Instructions for a particular control may also list properties
that are specific to that control.
6-20
Add Components to the GUIDE Layout Area
For a complete list of properties and for more information about the properties listed in
the table, see Uicontrol.
Push Button
6-21
6 Lay Out a UI Using GUIDE
• Specify the push button label by setting the String property to the desired label, in
this case, Button 1.
To display the & character in a label, use two & characters. The words remove,
default, and factory (case sensitive) are reserved. To use one of these as a label,
prepend a backslash character (\). For example, \remove yields remove.
The push button accommodates only a single line of text. If you specify more than one
line, only the first line is shown. If you create a push button that is too narrow to
accommodate the specified String property value, MATLAB truncates the value with
an ellipsis.
6-22
Add Components to the GUIDE Layout Area
• If you want to set the position or size of the component to an exact value, then modify
its Position property.
• To add an image to a push button, assign the button's CData property as an m-by-n-
by-3 array of RGB values that defines a truecolor image. You must do this
programmatically in the opening function of the code file. For example, the array img
defines a 16-by-64-by-3 truecolor image using random values between 0 and 1
(generated by rand).
img = rand(16,64,3);
set(handles.pushbutton1,'CData',img);
Slider
6-23
6 Lay Out a UI Using GUIDE
• Specify the range of the slider by setting its Min property to the minimum value of the
slider and its Max property to the maximum value. The Min property must be less than
Max.
• Specify the value indicated by the slider when it is created by setting the Value
property to the appropriate number. This number must be less than or equal to Max
and greater than or equal to Min. If you specify Value outside the specified range, the
slider is not displayed.
• The slider Value changes by a small amount when a user clicks the arrow button, and
changes by a larger amount when the user clicks the trough (also called the channel).
Control how the slider responds to these actions by setting the SliderStep property.
Specify SliderStep as a two-element vector, [minor_step major_step], where
minor_step is less than or equal to major_step. Because specifying very small
values can cause unpredictable slider behavior, make both minor_step and
major_step greater than 1e-6. Set major_step to the proportion of the range that
clicking the trough moves the slider thumb. Setting it to 1 or higher causes the thumb
to move to Max or Min when the trough is clicked.
6-24
Add Components to the GUIDE Layout Area
• If you want to set the location or size of the component to an exact value, then modify
its Position property.
The slider component provides no text description or data entry capability. Use a
“Static Text” on page 6-30 component to label the slider. Use an “Edit Text” on page
6-28 component to enable a user to input a value to apply to the slider.
Note On Mac platforms, the height of a horizontal slider is constrained. If the height
you set in the position vector exceeds this constraint, the displayed height of the slider
is the maximum allowed. The height element of the position vector is not changed.
Radio Button
To create a radio button with label Indent nested functions, as shown in this figure:
• Specify the radio button label by setting the String property to the desired label, in
this case, Indent nested functions.
6-25
6 Lay Out a UI Using GUIDE
To display the & character in a label, use two & characters. The words remove,
default, and factory (case sensitive) are reserved. To use one of these as a label,
prepend a backslash character (\). For example, \remove yields remove.
The radio button accommodates only a single line of text. If you specify more than one
line, only the first line is shown. If you create a radio button that is too narrow to
accommodate the specified String property value, MATLAB software truncates the
value with an ellipsis.
• Create the radio button with the button selected by setting its Value property to the
value of its Max property (default is 1). Set Value to Min (default is 0) to leave the
radio button unselected. Correspondingly, when the user selects the radio button, the
software sets Value to Max, and to Min when the user deselects it.
• If you want to set the position or size of the component to an exact value, then modify
its Position property.
• To add an image to a radio button, assign the button's CData property an m-by-n-by-3
array of RGB values that defines a truecolor image. You must do this programmatically
in the opening function of the code file. For example, the array img defines a 16-by-24-
by-3 truecolor image using random values between 0 and 1 (generated by rand).
img = rand(16,24,3);
set(handles.radiobutton1,'CData',img);
Note To manage exclusive selection of radio buttons and toggle buttons, put them in a
button group. See “Button Group” on page 6-43 for more information.
6-26
Add Components to the GUIDE Layout Area
Check Box
To create a check box with label Display file extension that is initially checked, as
shown in this figure:
• Specify the check box label by setting the String property to the desired label, in this
case, Display file extension.
To display the & character in a label, use two & characters. The words remove,
default, and factory (case sensitive) are reserved. To use one of these as a label,
prepend a backslash character (\). For example, \remove yields remove.
The check box accommodates only a single line of text. If you specify a component
width that is too small to accommodate the specified String property value, MATLAB
software truncates the value with an ellipsis.
6-27
6 Lay Out a UI Using GUIDE
• Create the check box with the box checked by setting the Value property to the value
of the Max property (default is 1). Set Value to Min (default is 0) to leave the box
unchecked. Correspondingly, when the user clicks the check box, the software sets
Value to Max when the user checks the box and to Min when the user clears it.
• If you want to set the position or size of the component to an exact value, then modify
its Position property.
Edit Text
To create an edit text component that displays the initial text Enter your name here, as
shown in this figure:
• Specify the text to be displayed when the edit text component is created by setting the
String property to the desired value, in this case, Enter your name here.
6-28
Add Components to the GUIDE Layout Area
To display the & character in a label, use two & characters. The words remove,
default, and factory (case sensitive) are reserved. To use one of these as a label,
prepend a backslash character (\). For example, \remove yields remove.
• To enable multiple-line input, specify the Max and Min properties so that their
difference is greater than 1. For example, Max = 2, Min = 0. Max default is 1, Min
default is 0. MATLAB software wraps the displayed text and adds a scroll bar if
necessary. On all platforms, when the user enters a multiline text box via the Tab key,
the editing cursor is placed at its previous location and no text highlights.
If Max-Min is less than or equal to 1, the edit text component allows only a single line
of input. If you specify a component width that is too small to accommodate the
specified text, MATLAB displays only part of that text. The user can use the arrow keys
to move the cursor through the text. On all platforms, when the user enters a single-
6-29
6 Lay Out a UI Using GUIDE
line text box via the Tab key, the entire contents is highlighted and the editing cursor
is at the end of the text.
• If you want to set the position or size of the component to an exact value, then modify
its Position property.
• You specify the text font to display in the edit box by typing the name of a font residing
on your system into the FontName entry in the Property Inspector. On Microsoft®
Windows® platforms, the default is MS Sans Serif; on Macintosh and UNIX®
platforms, the default is Helvetica.
Tip To find out what fonts are available, type uisetfont at the MATLAB prompt; a
dialog displays containing a list box from which you can select and preview available
fonts. When you select a font, its name and other characteristics are returned in a
structure, from which you can copy the FontName and paste it into the Property
Inspector. Not all fonts listed may be available on other systems.
Static Text
To create a static text component with text Select a data set, as shown in this figure:
6-30
Add Components to the GUIDE Layout Area
• Specify the text that appears in the component by setting the component String
property to the desired text, in this case Select a data set.
To display the & character in a list item, use two & characters. The words remove,
default, and factory (case sensitive) are reserved. To use one of these as a label,
prepend a backslash character (\). For example, \remove yields remove.
If your component is not wide enough to accommodate the specified value, MATLAB
wraps the displayed text.
6-31
6 Lay Out a UI Using GUIDE
• If you want to set the position or size of the component to an exact value, then modify
its Position property.
• You can specify a text font, including its FontName, FontWeight, FontAngle,
FontSize, and FontUnits properties. For details, see the previous topic, “Edit Text”
on page 6-28, and for a programmatic approach, the section “How to Set Font
Characteristics” on page 9-22.
Pop-Up Menu
To create a pop-up menu (also known as a drop-down menu or combo box) with items
one, two, three, and four, as shown in this figure:
• Specify the pop-up menu items to be displayed by setting the String property to the
desired items. Click the
button to the right of the property name to open the Property Inspector editor.
6-32
Add Components to the GUIDE Layout Area
To display the & character in a menu item, use two & characters. The words remove,
default, and factory (case sensitive) are reserved. To use one of these as a label,
prepend a backslash character (\). For example, \remove yields remove.
If the width of the component is too small to accommodate one or more of the menu
items, MATLAB truncates those items with an ellipsis.
• To select an item when the component is created, set Value to a scalar that indicates
the index of the selected list item, where 1 corresponds to the first item in the list. If
you set Value to 2, the menu looks like this when it is created:
6-33
6 Lay Out a UI Using GUIDE
• If you want to set the position and size of the component to exact values, then modify
its Position property. The height of a pop-up menu is determined by the font size.
The height you set in the position vector is ignored.
Note The pop-up menu does not provide for a label. Use a “Static Text” on page 6-30
component to label the pop-up menu.
List Box
To create a list box with items one, two, three, and four, as shown in this figure:
6-34
Add Components to the GUIDE Layout Area
• Specify the list of items to be displayed by setting the String property to the desired
list. Use the Property Inspector editor to enter the list. You can open the editor by
6-35
6 Lay Out a UI Using GUIDE
To display the & character in a label, use two & characters. The words remove,
default, and factory (case sensitive) are reserved. To use one of these as a label,
prepend a backslash character (\). For example, \remove yields remove.
If the width of the component is too small to accommodate one or more of the
specified list items, MATLAB software truncates those items with an ellipsis.
• Specify selection by using the Value property together with the Max and Min
properties.
• To select a single item when the component is created, set Value to a scalar that
indicates the index of the selected list item, where 1 corresponds to the first item in
the list.
• To select more than one item when the component is created, set Value to a vector
of indices of the selected items. Value = [1,3] results in the following selection.
6-36
Add Components to the GUIDE Layout Area
To enable selection of more than one item, you must specify the Max and Min
properties so that their difference is greater than 1. For example, Max = 2, Min =
0. Max default is 1, Min default is 0.
• If you want no initial selection, set the Max and Min properties to enable multiple
selection, i.e., Max - Min > 1, and then set the Value property to an empty
matrix [].
• If the list box is not large enough to display all list entries, you can set the
ListBoxTop property to the index of the item you want to appear at the top when the
component is created.
• If you want to set the position or size of the component to an exact value, then modify
its Position property.
Note The list box does not provide for a label. Use a “Static Text” on page 6-30
component to label the list box.
Toggle Button
To create a toggle button with label Left/Right Tile, as shown in this figure:
6-37
6 Lay Out a UI Using GUIDE
• Specify the toggle button label by setting its String property to the desired label, in
this case, Left/Right Tile.
To display the & character in a label, use two & characters. The words remove,
default, and factory (case sensitive) are reserved. To use one of these as a label,
prepend a backslash character (\). For example, \remove yields remove.
The toggle button accommodates only a single line of text. If you specify more than
one line, only the first line is shown. If you create a toggle button that is too narrow to
accommodate the specified String value, MATLAB truncates the text with an ellipsis.
6-38
Add Components to the GUIDE Layout Area
• Create the toggle button with the button selected (depressed) by setting its Value
property to the value of its Max property (default is 1). Set Value to Min (default is 0)
to leave the toggle button unselected (raised). Correspondingly, when the user selects
the toggle button, MATLAB software sets Value to Max, and to Min when the user
deselects it. The following figure shows the toggle button in the depressed position.
• If you want to set the position or size of the component to an exact value, then modify
its Position property.
• To add an image to a toggle button, assign the button's CData property an m-by-n-by-3
array of RGB values that defines a truecolor image. You must do this programmatically
in the opening function of the code file. For example, the array img defines a 16-by-64-
by-3 truecolor image using random values between 0 and 1 (generated by rand).
img = rand(16,64,3);
set(handles.togglebutton1,'CData',img);
Note To manage exclusive selection of radio buttons and toggle buttons, put them in a
button group. See “Button Group” on page 6-43 for more information.
6-39
6 Lay Out a UI Using GUIDE
To define panels and button groups, you must set certain properties. To do this:
1 Use the Property Inspector to modify the appropriate properties. Open the Property
Inspector by selecting View > Property Inspector or by clicking the Property
Inspector button .
2 In the layout area, select the component you are defining.
Subsequent topics describe commonly used properties of panels and button groups and
offer a simple example for each component.
The most commonly used properties needed to describe a panel or button group are
shown in the following table:
6-40
Add Components to the GUIDE Layout Area
For a complete list of properties and for more information about the properties listed in
the table, see the Uipanel and Uibuttongroup.
Panel
• Specify the panel title by setting the Title property to the desired value, in this case
My Panel.
6-41
6 Lay Out a UI Using GUIDE
To display the & character in the title, use two & characters. The words remove,
default, and factory (case sensitive) are reserved. To use one of these as a label,
prepend a backslash character (\). For example, \remove yields remove.
• Specify the location of the panel title by selecting one of the available
TitlePosition property values from the pop-up menu, in this case lefttop. You
can position the title at the left, middle, or right of the top or bottom of the panel.
6-42
Add Components to the GUIDE Layout Area
• If you want to set the position or size of the panel to an exact value, then modify its
Position property.
Button Group
To create a button group with title My Button Group as shown in the following figure:
6-43
6 Lay Out a UI Using GUIDE
• Specify the button group title by setting the Title property to the desired value, in
this case My Button Group.
6-44
Add Components to the GUIDE Layout Area
To display the & character in the title, use two & characters. The words remove,
default, and factory (case sensitive) are reserved. To use one of these as a label,
prepend a backslash characters (\). For example, \remove yields remove.
• Specify the location of the button group title by selecting one of the available
TitlePosition property values from the pop-up menu, in this case lefttop. You
can position the title at the left, middle, or right of the top or bottom of the button
group.
• If you want to set the position or size of the button group to an exact value, then
modify its Position property.
Axes
Axes allow you to display graphics such as graphs and images using commands such as:
plot, surf, line, bar, polar, pie, contour, and mesh.
6-45
6 Lay Out a UI Using GUIDE
1 Use the Property Inspector to modify the appropriate properties. Open the Property
Inspector by selecting View > Property Inspector or by clicking the Property
Inspector button .
2 In the layout area, select the component you are defining.
Subsequent topics describe commonly used properties of axes and offer a simple example.
The most commonly used properties needed to describe an axes are shown in the
following table:
For a complete list of properties and for more information about the properties listed in
the table, see Axes.
See commands such as the following for more information on axes objects: plot, surf,
line, bar, polar, pie, contour, imagesc, and mesh.
Many of these graphing functions reset axes properties by default, according to the
setting of its NextPlot property, which can cause unwanted behavior, such as resetting
axis limits and removing axes context menus and callbacks. See “Create Axes” on page 6-
47 and “Axes” on page 9-20 for information about setting the NextPlot property.
6-46
Add Components to the GUIDE Layout Area
Create Axes
• Allow for tick marks to be placed outside the box that appears in the Layout Editor.
The axes above looks like this in the layout editor; placement allows space at the left
and bottom of the axes for tick marks. Functions that draw in the axes update the tick
marks appropriately.
6-47
6 Lay Out a UI Using GUIDE
• Use the title, xlabel, ylabel, zlabel, and text functions in the code file to label
an axes component. For example,
xlh = (axes_handle,'Years')
labels the X-axis as Years. The handle of the X-axis label is xlh.
The words remove, default, and factory (case sensitive) are reserved. To use one
of these in component text, prepend a backslash character (\). For example, \remove
yields remove.
• If you want to set the position or size of the axes to an exact value, then modify its
Position property.
6-48
Add Components to the GUIDE Layout Area
• If you customize axes properties, some of them (or example, callbacks, font
characteristics, and axis limits and ticks) may get reset to default every time you draw
a graph into the axes when the NextPlot property has its default value of
'replace'. To keep customized properties as you want them, set NextPlot to
'replacechildren' in the Property Inspector, as shown here.
Table
Tables enable you to display data in a two dimensional table. You can use the Property
Inspector to get and set the object property values.
The most commonly used properties of a table component are listed in the table below.
These are grouped in the order they appear in the Table Property Editor. Please refer to
uitable documentation for detail of all the table properties:
6-49
6 Lay Out a UI Using GUIDE
Create a Table
6-50
Add Components to the GUIDE Layout Area
Drag the table icon on to the Layout Editor and right click in the table. From the table’s
context menu, select Table Property Editor. You can also select Table Property Editor
from the Tools menu when you select a table by itself.
6-51
6 Lay Out a UI Using GUIDE
When you open it this way, the Table Property Editor displays the Column pane. You can
also open it from the Property Inspector by clicking one of its Table Property Editor icons
, in which case the Table Property Editor opens to display the pane appropriate for the
property you clicked.
Clicking items in the list on the left hand side of the Table Property Editor changes the
contents of the pane to the right . Use the items to activate controls for specifying the
table's Columns, Rows, Data, and Color options.
The Columns and Rows panes each have a data entry area where you can type names
and set properties. on a per-column or per-row basis. You can edit only one row or column
6-52
Add Components to the GUIDE Layout Area
definition at a time. These panes contain a vertical group of five buttons for editing and
navigating:
Keyboard equivalents only operate when the cursor is in the data entry area. In addition
to those listed above, typing Ctrl+T or Cmd+T selects the entire field containing the
cursor for editing (if the field contains text).
To save changes to the table you make in the Table Property Editor, click OK, or click
Apply commit changes and keep on using the Table Property Editor.
Set Column Properties
6-53
6 Lay Out a UI Using GUIDE
Select Show names entered below as the column headers and set the ColumnName
by entering Rate, Amount, Available, and Fixed/Adj in Name group. for the Available and
Fixed/Adj columns set the ColumnEditable property to on. Lastly set the
ColumnFormat for the four columns
6-54
Add Components to the GUIDE Layout Area
For the Rate column, select Numeric. For the Amount Column select Custom and in the
Custom Format Editor, choose Bank.
6-55
6 Lay Out a UI Using GUIDE
Leave the Available column at the default value. This allows MATLAB to chose based on
the value of the Data property of the table. For the Fixed/Adj column select Choice
List to create a pop-up menu. In the Choice List Editor, click Insert to add a second
choice and type Fixed and Adjustable as the 2 choices.
6-56
Add Components to the GUIDE Layout Area
Note For a user to select items from a choice list, the ColumnEditable property of the
column that the list occupies must be set to 'true'. The pop-up control only appears
when the column is editable.
In the Row tab, leave the default RowName, Show numbered row headers.
6-57
6 Lay Out a UI Using GUIDE
Use the Data property to specify the data in the table. Create the data in the command
window before you specify it in GUIDE. For this example, type:
In the Table Property Editor, select the data that you defined and select Change data
value to the selected workspace variable below.
6-58
Add Components to the GUIDE Layout Area
Specify the BackgroundColor and RowStriping for your table in the Color tab.
6-59
6 Lay Out a UI Using GUIDE
You can change other uitable properties to the table via the Property Inspector.
ActiveX Component
When you drag an ActiveX component from the component palette into the layout area,
GUIDE opens a dialog box, similar to the following, that lists the registered ActiveX
controls on your system.
Note If MATLAB software is not installed locally on your computer — for example, if you
are running the software over a network — you might not find the ActiveX control
described in this example. To register the control, see “Registering Controls and Servers”.
6-60
Add Components to the GUIDE Layout Area
1 Select the desired ActiveX control. The right panel shows a preview of the selected
control.
2 Click Create. The control appears as a small box in the Layout Editor.
3 Resize the control to approximately the size of the square shown in the preview pane.
You can do this by clicking and dragging a corner of the control, as shown in the
following figure.
6-61
6 Lay Out a UI Using GUIDE
When you select an ActiveX control, you can open the ActiveX Property Editor by right-
clicking and selecting ActiveX Property Editor from the context menu or clicking the
Tools menu and selecting it from there.
Note What an ActiveX Property Editor contains and looks like is dependent on what
user controls that the authors of the particular ActiveX object have created and stored in
the UI for the object. In some cases, a UI without controls or no UI at all appears when
you select this menu item.
Select the component you want to resize. Click one of the corner handles and drag it until
the component is the desired size.
6-62
Add Components to the GUIDE Layout Area
Select one or more components that you want to resize. Then select View > Property
Inspectoror click the Property Inspector button .
1 In the Property Inspector, scroll to the Units property and note whether the current
setting is characters or normalized. Click the button next to Units and then
change the setting to inches from the pop-up menu.
6-63
6 Lay Out a UI Using GUIDE
2 Click the + sign next to Position. The Property Inspector displays the elements of
the Position property.
3 Type the width and height you want the components to be.
4 Reset the Units property to its previous setting, either characters or
normalized.
Note To select multiple components, they must have the same parent. That is, they must
be contained in the same figure, panel, or button group. Setting the Units property to
characters (nonresizable UIs) or normalized (resizable UIs) gives the UI a more
consistent appearance across platforms.
See Also
Related Examples
• “Ways to Build Apps” on page 1-2
• “Create a Simple App Using GUIDE” on page 2-2
• “Write Callbacks in GUIDE” on page 7-2
6-64
See Also
6-65
6 Lay Out a UI Using GUIDE
Note To select multiple components, they must have the same parent. That is, they must
be contained in the same figure, panel, or button group.
6-66
Align GUIDE UI Components
Both types of alignment can be applied in the vertical and horizontal directions. In many
cases, it is better to apply alignments independently to the vertical and horizontal using
two separate steps.
Align Options
There are both vertical and horizontal align options. Each option aligns selected
components to a reference line, which is determined by the bounding box that encloses
the selected objects. For example, the following picture of the layout area shows the
bounding box (indicated by the dashed line) formed by three selected push buttons.
6-67
6 Lay Out a UI Using GUIDE
All of the align options (vertical top, center, bottom and horizontal left, center, right) place
the selected components with respect to the corresponding edge (or center) of this
bounding box.
Distribute Options
Distributing components adds equal space between all components in the selected group.
The distribute options operate in two different modes:
• Default behavior — MATLAB distributes space equally among components within the
bounding box.
• Select the Set spacing check box — You specify the number of pixels between each
component.
Both modes enable you to specify how the spacing is measured, as indicated by the button
labels on the alignment tool. These options include spacing measured with respect to the
following edges:
6-68
Align GUIDE UI Components
Property Inspector
About the Property Inspector
In GUIDE, as in MATLAB generally, you can see and set most components' properties
using the Property Inspector. To open it from the GUIDE Layout Editor, do any of the
following:
• Select the component you want to inspect, or double-click it to open the Property
Inspector and bring it to the foreground
• Select View > Property Inspector.
• Click the Property Inspector button
The Property Inspector window opens, displaying the properties of the selected
component. For example, here is a view of a push button's properties.
6-69
6 Lay Out a UI Using GUIDE
Scroll down to see additional properties. Click any property value or icon to set its value.
The Property Inspector provides context-sensitive help for individual properties. To see a
definition of any property, right-click the name or value in the Property Inspector and
click the What's This? menu item that appears. A context-sensitive help window opens
displaying the definition of the property.
6-70
Align GUIDE UI Components
6-71
6 Lay Out a UI Using GUIDE
The Property Inspector enables you to align components by setting their Position
properties. A component's Position property is a four-element vector that specifies the
size and location of the component: [distance from left, distance from bottom, width,
height]. The values are given in the units specified by the Units property of the
component.
1 Select the components you want to align.
2 Select View > Property Inspector or click the Property Inspector button .
3 In the Property Inspector, scroll to the Units property and note its current setting,
then change the setting to inches.
4 Scroll to the Position property. This figure shows the Position property for
multiple components of the same size.
5 Change the value of x to align their left sides. Change the value of y to align their
bottom edges. For example, setting x to 2.0 aligns the left sides of the components 2
inches from the left side of the window.
6 When the components are aligned, change the Units property back to its original
setting.
6-72
Align GUIDE UI Components
You can optionally enable snap-to-grid, which causes any object that is moved close to a
grid line to jump to that line. Snap-to-grid works with or without a visible grid.
Use the Grid and Rulers dialog (select Tools > Grid and Rulers) to:
Guide Lines
The Layout Editor has both vertical and horizontal snap-to guide lines. Components snap
to the line when you move them close to the line.
Guide lines are useful when you want to establish a reference for component alignment at
an arbitrary location in the Layout Editor.
To create a guide line, click the top or left ruler and drag the line into the layout area.
6-73
6 Lay Out a UI Using GUIDE
See Also
Related Examples
• “GUIDE Options” on page 5-8
6-74
Customize Tabbing Behavior in a GUIDE UI
You can set, independently, the tab order of components that have the same parent. The
figure window, each panel, and each button group has its own tab order. For example, you
can set the tab order of components that have the figure as a parent. You can also set the
tab order of components that have a panel or button group as a parent.
If, in tabbing through the components at the figure level, a user tabs to a panel or button
group, then subsequent tabs sequence through the components of the panel or button
group before returning to the level from which the panel or button group was reached.
Note Axes cannot be tabbed. From GUIDE, you cannot include ActiveX components in
the tab order.
When you create a UI, GUIDE sets the tab order at each level to be the order in which you
add components to that level in the Layout Editor. This may not be the best order for the
user.
Note Tab order also affects the stacking order of components. If components overlap,
those that appear lower in the tabbing order, are drawn on top of those that appear
higher in the order.
The following UI contains an axes component, a slider, a panel, static text, and a pop-up
menu. Of these, only the slider, the panel, and the pop-up menu at the figure level can be
tabbed. The panel contains three push buttons, which can all be tabbed.
6-75
6 Lay Out a UI Using GUIDE
To examine and change the tab order of the panel components, click the panel
background to select it, then select Tools > Tab Order Editor in the Layout Editor.
6-76
Customize Tabbing Behavior in a GUIDE UI
The Tab Order Editor displays the panel's components in their current tab order. To
change the tab order, select a component and press the up or down arrow to move the
component up or down in the list. If you set the tab order for the first three components
in the example to be
the user first tabs to the Surf push button, then to the Contour push button, and then to
the Mesh push button. Subsequent tabs sequence through the remaining components at
the figure level.
6-77
6 Lay Out a UI Using GUIDE
You can use GUIDE to create menu bars (containing pull-down menus) as well as context
menus that you attach to components. You can create both types of menus using the
Menu Editor. Access the Menu Editor from the Tools menu or click the Menu Editor
button .
6-78
Create Menus for GUIDE Apps
When you create a drop-down menu, GUIDE adds its title to the menu bar. You then can
create menu items for that menu. Each menu item can have a cascading menu, also
known as a submenu, and these items can have cascading menus, and so on.
By default, when you create a UI with GUIDE, it does not create a menu bar for that UI.
You might not need menus for your UI, but if you want the user to be able to dock or
undock the UI window, it must contain a menu bar or a toolbar. This is because docking is
controlled by the docking icon, a small curved arrow near the upper-right corner of the
menu bar or the toolbar, as the following illustration shows.
Figure windows with a standard menu bar also have a Desktop menu from which the
user can dock and undock them.
To display the docking arrow and the Desktop > Dock Figure menu item, use the
Property Inspector to set the figure property DockControls to 'on'. You must also set
the MenuBar and/or ToolBar figure properties to 'figure' to display docking controls.
The WindowStyle figure property also affects docking behavior. The default is
'normal', but if you change it to 'docked', then the following applies:
• The UI window opens docked in the desktop when you run it.
6-79
6 Lay Out a UI Using GUIDE
• The DockControls property is set to 'on' and cannot be turned off until
WindowStyle is no longer set to 'docked'.
• If you undock a UI window created with WindowStyle 'docked', it will have not
have a docking arrow unless the figure displays a menu bar or a toolbar (either
standard or customized). When it has no docking arrow, users can undock it from the
desktop, but will be unable to redock it there.
However, when you provide your own menu bar or toolbar using GUIDE, it can display the
docking arrow if you want the UI window to be dockable. See the following sections and
“Create Toolbars for GUIDE UIs” on page 6-95 for details.
Note UIs that are modal dialogs (figures with WindowStyle set to 'modal') cannot
have menu bars, toolbars, or docking controls.
For more information, see the DockControls, MenuBar, ToolBar, and WindowStyle
property descriptions in Figure.
The figure MenuBar property controls whether your UI displays the MATLAB standard
menus on the menu bar. GUIDE initially sets the value of MenuBar to none. If you want
your UI to display the MATLAB standard menus, use the Property Inspector to set
MenuBar to figure.
• If the value of MenuBar is none, GUIDE automatically adds a menu bar that displays
only the menus you create.
• If the value of MenuBar is figure, the UI displays the MATLAB standard menus and
GUIDE adds the menus you create to the right side of the menu bar.
In either case, you can enable the user to dock and undock the window by setting the
figure's DockControls property to 'on'.
Create a Menu
1 Start a new menu by clicking the New Menu button in the toolbar. A menu title,
Untitled 1, appears in the left pane of the dialog box.
6-80
Create Menus for GUIDE Apps
Note By default, GUIDE selects the Menu Bar tab when you open the Menu Editor.
2 Click the menu title to display a selection of menu properties in the right pane.
6-81
6 Lay Out a UI Using GUIDE
3 Fill in the Text and Tag fields for the menu. For example, set Text to File and set
Tag to file_menu. Click outside the field for the change to take effect.
Text is a text label for the menu item. To display the & character in a label, use two &
characters. The words remove, default, and factory (case sensitive) are reserved.
To use one of these as labels, prepend a backslash character (\). For example,
\remove yields remove.
Tag is a character vector that serves as an identifier for the menu object. It is used in
the code to identify the menu item and must be unique in your code file.
Use the New Menu Item tool to create menu items that are displayed in the drop-down
menu.
6-82
Create Menus for GUIDE Apps
1 Add an Open menu item under File, by selecting File then clicking the New Menu
Item button in the toolbar. A temporary numbered menu item label, Untitled,
appears.
2 Fill in the Text and Tag fields for the new menu item. For example, set Text to Open
and set Tag to menu_file_open. Click outside the field for the change to take effect.
6-83
6 Lay Out a UI Using GUIDE
• Choose an alphabetic keyboard accelerator for the menu item with the Accelerator
pop-up menu. In combination with Ctrl, this is the keyboard equivalent for a menu
item that does not have a child menu. Note that some accelerators may be used for
other purposes on your system and that other actions may result.
• Display a separator above the menu item by checking Separator above this item.
• Display a check next to the menu item when the menu is first opened by checking
Check mark this item. A check indicates the current state of the menu item. See the
example in “Add Items to the Context Menu” on page 6-90.
• Enable this item when the menu is first opened by checking Enable this item. This
allows the user to select this item when the menu is first opened. If you clear this
option, the menu item appears dimmed when the menu is first opened, and the user
cannot select it.
6-84
Create Menus for GUIDE Apps
• Specify the Callback function that executes when the users selects the menu item. If
you have not yet saved the UI, the default value is %automatic. When you save the
UI, and if you have not changed this field, GUIDE automatically sets the value using a
combination of the Tag field and the UI file name. See “Menu Item” on page 7-22 for
more information about specifying this field and for programming menu items.
The View button displays the callback, if there is one, in an editor. If you have not yet
saved the UI, GUIDE prompts you to save it.
• Open the Property Inspector, where you can change all menu properties, by clicking
the More Properties button. For detailed information about the properties, see
Uimenu.
Note See “Menu Item” on page 7-22 and “How to Update a Menu Item Check” on page
7-24 for programming information and basic examples.
To create additional drop-down menus, use the New Menu button in the same way you did
to create the File menu. For example, the following figure also shows an Edit drop-
down menu.
Cascading Menus
To create a cascading menu, select the menu item that will be the title for the cascading
menu, then click the New Menu Item button. In the example below, Edit is a cascading
menu.
6-85
6 Lay Out a UI Using GUIDE
Note See “Menu Item” on page 7-22 for information about programming menu items.
The following Menu Editor illustration shows three menus defined for the figure menu
bar.
6-86
Create Menus for GUIDE Apps
When you run the app, the menu titles appear in the menu bar.
6-87
6 Lay Out a UI Using GUIDE
Context Menus
A context menu is displayed when a user right-clicks the object for which the menu is
defined. The Menu Editor enables you to define context menus and associate them with
objects in the layout. The process has three steps:
Note See “Menus for the Menu Bar” on page 6-78 for information about defining menus
in general. See “Menu Item” on page 7-22 for information about defining local callback
functions for your menus.
6-88
Create Menus for GUIDE Apps
All items in a context menu are children of a menu that is not displayed on the figure
menu bar. To define the parent menu:
1 Select the Menu Editor's Context Menus tab and select the New Context Menu
button from the toolbar.
2 Select the menu, and in the Tag field type the context menu tag
(axes_context_menu in this example).
6-89
6 Lay Out a UI Using GUIDE
Use the New Menu Item button to create menu items that are displayed in the context
menu.
6-90
Create Menus for GUIDE Apps
2 Fill in the Text and Tag fields for the new menu item. For example, set Text to Blue
background color and set Tag to blue_background. Click outside the field for
the change to take effect.
6-91
6 Lay Out a UI Using GUIDE
• Display a separator above the menu item by checking Separator above this item.
• Display a check next to the menu item when the menu is first opened by checking
Check mark this item. A check indicates the current state of the menu item. See the
example in “Add Items to the Context Menu” on page 6-90. See “How to Update a
Menu Item Check” on page 7-24 for a code example.
• Enable this item when the menu is first opened by checking Enable this item. This
allows the user to select this item when the menu is first opened. If you clear this
option, the menu item appears dimmed when the menu is first opened, and the user
cannot select it.
• Specify a Callback for the menu that performs the action associated with the menu
item. If you have not yet saved the UI, the default value is %automatic. When you
save the UI, and if you have not changed this field, GUIDE automatically creates a
callback in the code file using a combination of the Tag field and the UI file name. The
6-92
Create Menus for GUIDE Apps
callback's name does not display in the Callback field of the Menu Editor, but
selecting the menu item does trigger it.
You can also type a command into the Callback field. It can be any valid MATLAB
expression or command. For example, this command
sets the current axes background color to yellow. However, the preferred approach to
performing this operation is to place the callback in the code file. This avoids the use
of gca, which is not always reliable when several figures or axes exist. Here is a
version of this callback coded as a function in the code file:
This code sets the background color of the axes with Tag axes1 no matter to what
object the context menu is attached to.
If you enter a callback value in the Menu Editor, it overrides the callback for the item
in the code file, if any has been saved. If you delete a value that you entered in the
Callback field, the callback for the item in the code file is executed when the user
selects that item in the UI.
See “Menu Item” on page 7-22 for more information about specifying this field and
for programming menu items. For another example of programming context menus in
GUIDE, see “GUIDE App Containing Tables and Plots” on page 8-12.
The View button displays the callback, if there is one, in an editor. If you have not yet
saved the UI, GUIDE prompts you to save it.
• Open the Property Inspector, where you can change all menu properties except
callbacks, by clicking the More Properties button. For detailed information about
these properties, see Uicontextmenu.
1 In the Layout Editor, select the object for which you are defining the context menu.
2 Use the Property Inspector to set this object's UIContextMenu property to the name
of the desired context menu.
6-93
6 Lay Out a UI Using GUIDE
The following figure shows the UIContextMenu property for the axes object with Tag
property axes1.
In the code file, complete the local callback function for each item in the context menu.
Each callback executes when a user selects the associated context menu item. See “Menu
Item” on page 7-22 for information on defining the syntax.
Note See “Menu Item” on page 7-22 and “How to Update a Menu Item Check” on page
7-24 for programming information and basic examples.
See Also
Related Examples
• “Write Callbacks in GUIDE” on page 7-2
• “Callbacks for Specific Components” on page 7-12
• “Create Toolbars for GUIDE UIs” on page 6-95
6-94
Create Toolbars for GUIDE UIs
In this section...
“Toolbar and Tools” on page 6-95
“Editing Tool Icons” on page 6-103
You can also open the Toolbar Editor from the Tools menu.
6-95
6 Lay Out a UI Using GUIDE
The Toolbar Editor gives you interactive access to all the features of the uitoolbar,
uipushtool, and uitoggletool functions. It only operates in the context of GUIDE;
you cannot use it to modify any of the built-in MATLAB toolbars. However, you can use the
Toolbar Editor to add, modify, and delete a toolbar from any UI in GUIDE.
Currently, you can add one toolbar to your UI in GUIDE. However, your UI can also
include the standard MATLAB figure toolbar. If you need to, you can create a toolbar that
looks like a normal figure toolbar, but customize its callbacks to make tools (such as pan,
zoom, and open) behave in specific ways.
Note You do not need to use the Toolbar Editor if you simply want your UI to have a
standard figure toolbar. You can do this by setting the figure's ToolBar property to
'figure', as follows:
6-96
Create Toolbars for GUIDE UIs
If you later want to remove the figure toolbar, set the ToolBar property to 'auto' and
resave the UI. Doing this will not remove or hide your custom toolbar. See “Create
Toolbars for Programmatic Apps” on page 9-51 for more information about making
toolbars manually.
If you want users to be able to dock and undock a UI window on the MATLAB desktop, it
must have a toolbar or a menu bar, which can either be the standard ones or ones you
create in GUIDE. In addition, the figure property DockControls must be turned on. For
details, see “How Menus Affect Figure Docking” on page 6-79.
6-97
6 Lay Out a UI Using GUIDE
To add a tool, drag an icon from the Tool Palette into the Toolbar Layout (which initially
contains the text prompt shown above), and edit the tool's properties in the Tool
Properties pane.
When you first create a UI, no toolbar exists on it. When you open the Toolbar Editor and
place the first tool, a toolbar is created and a preview of the tool you just added appears
in the top part of the window. If you later open a UI that has a toolbar, the Toolbar Editor
shows the existing toolbar, although the Layout Editor does not.
Add Tools
6-98
Create Toolbars for GUIDE UIs
Dragging allows you to place a tool in any order on the toolbar. The other two methods
place the tool to the right of the right-most tool on the Toolbar Layout. The new tool is
selected (indicated by a dashed box around it) and its properties are shown in the Tool
Properties pane. You can select only one tool at a time. You can cycle through the Tool
Palette using the tab key or arrow keys on your computer keyboard. You must have
placed at least one tool on the toolbar.
After you place tools from the Tool Palette into the Toolbar Layout area, the Toolbar
Editor shows the properties of the currently selected tool, as the following illustration
shows.
6-99
6 Lay Out a UI Using GUIDE
Predefined Tools
The set of icons on the bottom of the Tool Palette represent standard MATLAB figure
tools. Their behavior is built in. Predefined tools that require an axes (such as pan and
zoom) do not exhibit any behavior in UIs lacking axes. The callback(s) defining the
behavior of the predefined tool are shown as %default, which calls the same function
that the tool calls in standard figure toolbars and menus (to open files, save figures,
change modes, etc.). You can change %default to some other callback to customize the
tool; GUIDE warns you that you will modify the behavior of the tool when you change a
callback field or click the View button next to it, and asks if you want to proceed or not.
Custom Tools
The two icons at the top of the Tool Palette create pushtools and toggletools. These have
no built-in behavior except for managing their appearance when clicked on and off.
Consequently, you need to provide your own callback(s) when you add one to your toolbar.
In order for custom tools to respond to clicks, you need to edit their callbacks to create
the behaviors you desire. Do this by clicking the View button next to the callback in the
Tool Properties pane, and then editing the callback in the Editor window.
Separators are vertical bars that set off tools, enabling you to group them visually. You
can add or remove a separator in any of three ways:
• Right-click on a tool's preview and select Show Separator, which toggles its
separator on and off.
• Check or clear the check box Separator to the left in the tool's property pane.
• Change the Separator property of the tool from the Property Inspector
After adding a separator, that separator appears in the Toolbar Layout to the left of the
tool. The separator is not a distinct object or icon; it is a property of the tool.
6-100
Create Toolbars for GUIDE UIs
Move Tools
If a tool has a separator to its left, the separator moves with the tool.
Remove Tools
You edit the appearance and behavior of the currently selected tool using the Tool
Properties pane, which includes controls for setting the most commonly used tool
properties:
See “Write Callbacks in GUIDE” on page 7-2 for details on programming the tool
callbacks. You can also access these and other properties of the selected tool with the
Property Inspector. To open the Property Inspector, click the More Properties button on
the Tool Properties pane.
6-101
6 Lay Out a UI Using GUIDE
To edit a selected toolbar icon, click the Edit button in the Tool Properties pane, next to
CData (icon) or right-click the Toolbar Layout and select Edit Icon from the context
menu. The Icon Editor opens with the tool’s CData loaded into it. For information about
editing icons, see “Use the Icon Editor” on page 6-104.
If you click an empty part of the toolbar or click the Toolbar Properties tab, you can edit
two of its properties:
The Tag property is initially set to uitoolbar1. The Visible property is set to on.
When on, the Visible property causes the toolbar to be displayed on the UI regardless
of the setting of the figure’s Toolbar property. If you want to toggle a custom toolbar as
you can built-in ones (from the View menu), you can create a menu item, a check box, or
other control to control its Visible property.
To access nearly all the properties for the toolbar in the Property Inspector, click More
Properties.
To try out your toolbar, click the Run button in the Layout Editor. The software asks if you
want to save changes to its .fig file first.
Remove a Toolbar
You can remove a toolbar completely—destroying it—from the Toolbar Editor, leaving your
UI without a toolbar (other than the figure toolbar, which is not visible by default). The
are two ways to remove a toolbar:
•
Click the Remove button on the right end of the toolbar.
• Right-click a blank area on the toolbar and select Remove Toolbar from the context
menu.
If you remove all the individual tools in the ways shown in “Remove Tools” on page 6-101
without removing the toolbar itself, your UI will contain an empty toolbar.
6-102
Create Toolbars for GUIDE UIs
When you close the Toolbar Editor, the current state of your toolbar is saved with the UI
you are editing. You do not see the toolbar in the Layout Editor, but you can run your
program to see it.
6-103
6 Lay Out a UI Using GUIDE
• Icon file name — The icon image file to be loaded for editing
• Import button — Opens a file dialog to select an existing icon file for editing
• Drawing tools — A group of four tools on the left side for editing icons
6-104
Create Toolbars for GUIDE UIs
The Toolbar Editor and Icon Editor are shown together below.
6-105
6 Lay Out a UI Using GUIDE
See Also
Related Examples
• “Write Callbacks in GUIDE” on page 7-2
• “Callbacks for Specific Components” on page 7-12
• “Create Menus for GUIDE Apps” on page 6-78
6-106
Design Cross-Platform UIs in GUIDE
If you have set the FontName property to a named font and want to return to the default
value, you can set the property to default. This ensures that the software uses the
system default at run-time.
As an alternative, use the set command to set the property in the code file. For example,
if there is a push button in your UI and its handle is stored in the pushbutton1 field of
the handles structure, then the statement
set(handles.pushbutton1,'FontName','default')
6-107
6 Lay Out a UI Using GUIDE
If you want to use a fixed-width font for a user interface control, set its FontName
property to fixedwidth. This special identifier ensures that your UI uses the standard
fixed-width font for the target platform.
You can find the name of the fixed-width font that is used on a given platform by querying
the root FixedWidthFontName property.
get(groot,'FixedWidthFontName')
You can specify an actual font name (such as Times or Courier) for the FontName
property. However, doing so may cause your UI to not look as you intended when run on a
different computer. If the target computer does not have the specified font, it will
substitute another font that may not look good in your UI or may not be the standard font
used for UIs on that system. Also, different versions of the same named font may have
different size requirements for a given set of characters.
If you use the default component background color, you can use that same color as the
background color for your UI. This provides a consistent look with respect to your UI and
other applications. To do this in GUIDE, check Options > Use system color scheme for
background on the Layout Editor Tools menu.
Note This option is available only if you first select the Generate FIG-file and MATLAB
File option.
6-108
Design Cross-Platform UIs in GUIDE
using the default figure Units of pixels does not produce a UI that looks the same on
all platforms.
For this reason, GUIDE defaults the Units property for the figure to characters.
System-Dependent Units
Character units are defined by characters from the default system font. The width of a
character unit equals the width of the letter x in the system font. The height of a
character unit is the distance between the baselines of two lines of text. Note that
character units are not square.
The default Units property might change if you change the resize behavior using Tools
> GUI Options. This table lists the default units for each of the Resize behavior options.
Resize Behavior Default Units for Figure Default Units for Other
Components
Non-resizable characters characters
Proportional characters normalized
Other (Use characters characters
SizeChangedFcn)
At, times it might be convenient to use other units, such as inches or centimeters.
However, to preserve the look of your UI on different computers, remember to change the
figure Units property back to the default units after completing your layout calculations.
For more information on the resize behavior options, see “GUIDE Options” on page 5-8.
Note GUIDE does not automatically adjust component units if you modify the figure's
Resize property programmatically or in the Property Inspector.
6-109
7
In this section...
“Callbacks for Different User Actions” on page 7-2
“GUIDE-Generated Callback Functions and Property Values” on page 7-4
“GUIDE Callback Syntax” on page 7-5
“Renaming and Removing GUIDE-Generated Callbacks” on page 7-6
This table lists the callback properties that are available, the user actions that trigger the
callback function, and the most common UI and graphics components that use them.
7-2
Write Callbacks in GUIDE
7-3
7 Programming a GUIDE App
After you add a uicontrol, uimenu, or uicontextmenu component to your UI, but
before you save it, GUIDE populates the Callback property with the value, %automatic.
This value indicates that GUIDE will generate a name for the callback function.
When you save your UI, GUIDE adds an empty callback function definition to your code
file, and it sets the control’s Callback property to be an anonymous function. This
function definition is an example of a GUIDE-generated callback function for a push
button.
function pushbutton1_Callback(hObject,eventdata,handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
end
If you save this UI with the name, myui, then GUIDE sets the push button’s Callback
property to the following value:
@(hObject,eventdata)myui('pushbutton1_Callback',hObject,eventdata,guidata(hObject))
7-4
Write Callbacks in GUIDE
argument is the name of the callback function. The last three arguments are provided by
MATLAB, and are discussed in the section, “GUIDE Callback Syntax” on page 7-5.
Note GUIDE does not automatically generate callback functions for other UI
components, such as tables, panels, or button groups. If you want any of these
components to execute a callback function, then you must create the callback by right-
clicking on the component in the layout, and selecting an item under View Callbacks in
the context menu.
For the callback function to accept additional arguments, you must put the additional
arguments at the end of the argument list in the function definition.
The eventdata argument provides detailed information to certain callback functions. For
example, if the end user triggers the KeyPressFcn, then MATLAB provides information
regarding the specific key (or combination of keys) that the end user pressed. If
eventdata is not available to the callback function, then MATLAB passes it as an empty
array. The following table lists the callbacks and components that use eventdata.
7-5
7 Programming a GUIDE App
GUIDE creates the name of a callback function by combining the component’s Tag
property and the callback property name. If you change the component’s Tag value, then
GUIDE changes the callback's name the next time you save the UI.
If you decide to change the Tag value after saving the UI, then GUIDE updates the
following items (assuming that all components have unique Tag values).
@(hObject,eventdata)myui('pushbutton1_Callback',...
hObject,eventdata,guidata(hObject))
Deleting Callbacks
You can delete a callback function when you want to remove or change the function that
executes when the end user performs a specific action. To delete a callback function:
7-6
See Also
1 Search and replace all instances that refer to the callback function in your code.
2 Open the UI in GUIDE and replace all instances that refer to the callback function in
the Property Inspector.
3 Delete the callback function.
See Also
Related Examples
• “Callbacks for Specific Components” on page 7-12
• “Anonymous Functions”
• “Share Data Among Callbacks” on page 11-2
7-7
7 Programming a GUIDE App
Opening Function
The opening function is the first callback in every GUIDE code file. It is executed just
before the UI is made visible to the user, but after all the components have been created,
i.e., after the components' CreateFcn callbacks, if any, have been run.
You can use the opening function to perform your initialization tasks before the user has
access to the UI. For example, you can use it to create data or to read data from an
external source. MATLAB passes any command-line arguments to the opening function.
GUIDE names the opening function by appending _OpeningFcn to the name of the UI.
This is an example of an opening function template as it might appear in the myui code
file.
% --- Executes just before myui is made visible.
function myui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to myui (see VARARGIN)
Input Arguments
The opening function has four input arguments hObject, eventdata, handles, and
varargin. The first three are the same as described in “GUIDE Callback Syntax” on page
7-5. the last argument, varargin, enables you to pass arguments from the command line
7-8
Initialize UI Components in GUIDE Apps
to the opening function. The opening function can take actions with them (for example,
setting property values) and also make the arguments available to callbacks by adding
them to the handles structure.
For more information about using varargin, see the varargin reference page and
“Support Variable Number of Inputs”.
Passing Object Properties to an Opening Function
You can pass property name-value pairs as two successive command line arguments when
you run your program. If you pass a name-value pair that corresponds to a figure
property, MATLAB sets the property automatically. For example, my_gui('Color',
'Blue') sets the background color of the UI window to blue.
If you want your program to accept an input argument that is not a valid figure property,
then your code must recognize and handle that argument. Otherwise, the argument is
ignored. The following example is from the opening function for the Modal Question
Dialog on page 6-8 template, available from the GUIDE Quick Start dialog box. The added
code opens the modal dialog with a message, specified from the command line or by
another program that calls this one. For example, this command displays the text, 'Do
you want to exit?' on the window.
To accept this name-value pair, you must customize the opening function because
'String' is not a valid figure property. The Modal Question Dialog template file contains
code to performs these tasks:
7-9
7 Programming a GUIDE App
The if block loops through the odd elements of varargin checking for property names
or aliases, and the case blocks assign the following (even) varargin element as a value
to the appropriate property of the figure or one of its components. You can add more
cases to handle additional property assignments that you want the opening function to
perform.
Output Function
The output function returns, to the command line, outputs that are generated during its
execution. It is executed when the opening function returns control and before control
returns to the command line. This means that you must generate the outputs in the
opening function, or call uiwait in the opening function to pause its execution while
other callbacks generate outputs.
7-10
See Also
GUIDE names the output function by appending _OutputFcn to the name of the UI. This
is an example of an output function template as it might appear in the myui code file.
% --- Outputs from this function are returned to the command line.
function varargout = myui_OutputFcn(hObject, eventdata,...
handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
Input Arguments
The output function has three input arguments: hObject, eventdata, and handles.
They are the same as described in “GUIDE Callback Syntax” on page 7-5.
Output Arguments
The output function has one output argument, varargout, which it returns to the
command line. By default, the output function assigns handles.output to varargout.
• Change the value of handles.output. It can be any valid MATLAB value including a
structure or cell array.
• Add output arguments to varargout. The varargout argument is a cell array. It can
contain any number of output arguments. By default, GUIDE creates just one output
argument, handles.output. To create an additional output argument, create a new
field in the handles structure and add it to varargout using a command similar to
varargout{2} = handles.second_output;
See Also
Related Examples
• “Create a Simple App Using GUIDE” on page 2-2
7-11
7 Programming a GUIDE App
If you are creating an app programmatically, (without GUIDE), then you can adapt the
example code into your code. To adapt an example into your code, omit the third input
argument, handles, from the function definition. Also, replace any references to the
handles array with the appropriate object handle. To associate the callback function
with the component, set the component's callback property to be a handle to the callback
function. For example, this command creates a push button component and sets the
Callback property to be a handle to the function, pushbutton1_callback.
pb =
uicontrol('Style','pushbutton','Callback',@pushbutton1_Callback);
Push Button
This code is an example of a push button callback function in GUIDE. Associate this
function with the push button Callback property to make it execute when the end user
clicks on the push button.
7-12
Callbacks for Specific Components
Toggle Button
This code is an example of a toggle button callback function in GUIDE. Associate this
function with the toggle button Callback property to make it execute when the end user
clicks on the toggle button.
function togglebutton1_Callback(hObject,eventdata,handles)
% hObject handle to togglebutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
The toggle button’s Value property matches the Min property when the toggle button is
up. The Value changes to the Max value when the toggle button is depressed. This
callback function gets the toggle button’s Value property and then compares it with the
Max and Min properties. If the button is depressed, then the function displays 'down' in
the Command Window. If the button is up, then the function displays 'up'.
Radio Button
This code is an example of a radio button callback function in GUIDE. Associate this
function with the radio button Callback property to make it execute when the end user
clicks on the radio button.
if (get(hObject,'Value') == get(hObject,'Max'))
7-13
7 Programming a GUIDE App
display('Selected');
else
display('Not selected');
end
The radio button’s Value property matches the Min property when the radio button is not
selected. The Value changes to the Max value when the radio button is selected. This
callback function gets the radio button’s Value property and then compares it with the
Max and Min properties. If the button is selected, then the function displays 'Selected'
in the Command Window. If the button is not selected, then the function displays 'Not
selected'.
Note Use a button group to manage exclusive selection behavior for radio buttons. See
“Button Group” on page 7-21 for more information.
Check Box
This code is an example of a check box callback function in GUIDE. Associate this
function with the check box Callback property to make it execute when the end user
clicks on the check box.
if (get(hObject,'Value') == get(hObject,'Max'))
display('Selected');
else
display('Not selected');
end
The check box’s Value property matches the Min property when the check box is not
selected. The Value changes to the Max value when the check box is selected. This
callback function gets the check box’s Value property and then compares it with the Max
and Min properties. If the check box is selected, the function displays 'Selected' in the
Command Window. If the check box is not selected, it displays 'Not selected'.
7-14
Callbacks for Specific Components
When the user types characters inside the text field and presses the Enter key, the
callback function retrieves those characters and displays them in the Command Window.
To enable users to enter multiple lines of text, set the Max and Min properties to numeric
values that satisfy Max - Min > 1. For example, set Max to 2, and Min to 0 to satisfy the
inequality. In this case, the callback function triggers when the end user clicks on an area
in the UI that is outside of the text field.
If you want to interpret the contents of an edit text field as numeric values, then convert
the characters to numbers using the str2double function. The str2double function
returns NaN for nonnumeric input.
This code is an example of an edit text field callback function that interprets the user’s
input as numeric values.
7-15
7 Programming a GUIDE App
uicontrol(hObject)
return
else
display(input);
end
When the end user enters values into the edit text field and presses the Enter key, the
callback function gets the value of the String property and converts it to a numeric
value. Then, it checks to see if the value is NaN (nonnumeric). If the input is NaN, then the
callback presents an error dialog box.
Slider
This code is an example of a slider callback function in GUIDE. Associate this function
with the slider Callback property to make it execute when the end user moves the
slider.
When the end user moves the slider, the callback function gets the current value of the
slider and displays it in the Command Window. By default, the slider’s range is [0, 1]. To
modify the range, set the slider’s Max and Min properties to the maximum and minimum
values, respectively.
List Box
Populate Items in the List Box
If you are developing an app using GUIDE, use the list box CreateFcn callback to add
items to the list box.
This code is an example of a list box CreateFcn callback that populates the list box with
the items, Red, Green, and Blue.
7-16
Callbacks for Specific Components
If you are developing an app programmatically (without GUIDE), then populate the list
box when you create it. For example:
function myui()
figure
uicontrol('Style','Listbox',...
'String',{'Red';'Green';'Blue'},...
'Position',[40 70 80 50]);
end
When the end user selects a list box item, the list box’s Value property changes to a
number that corresponds to the item’s position in the list. For example, a value of 1
corresponds to the first item in the list. If you want to change the selection in your code,
then change the Value property to another number between 1 and the number of items
in the list.
For example, you can use the handles structure in GUIDE to access the list box and
change the Value property:
set(handles.listbox1,'Value',2)
7-17
7 Programming a GUIDE App
This code is an example of a list box callback function in GUIDE. Associate this function
with the list box Callback property to make it execute when a selects an item in the list
box.
function listbox1_Callback(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns contents
% contents{get(hObject,'Value')} returns selected item from listbox1
items = get(hObject,'String');
index_selected = get(hObject,'Value');
item_selected = items{index_selected};
display(item_selected);
When the end user selects an item in the list box, the callback function performs the
following tasks:
• Gets all the items in the list box and stores them in the variable, items.
• Gets the numeric index of the selected item and stores it in the variable,
index_selected.
• Gets the value of the selected item and stores it in the variable, item_selected.
• Displays the selected item in the MATLAB Command Window.
The example, “Interactive List Box App in GUIDE” on page 8-16 shows how to populate a
list box with directory names.
Pop-Up Menu
Populate Items in the Pop-Up Menu
If you are developing an app using GUIDE, use the pop-up menu CreateFcn callback to
add items to the pop-up menu.
This code is an example of a pop-up menu CreateFcn callback that populates the menu
with the items, Red, Green, and Blue.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
7-18
Callbacks for Specific Components
If you are developing an app programmatically (without GUIDE), then populate the pop-
up menu when you create it. For example:
function myui()
figure
uicontrol('Style','popupmenu',...
'String',{'Red';'Green';'Blue'},...
'Position',[40 70 80 20]);
end
When the end user selects an item, the pop-up menu’s Value property changes to a
number that corresponds to the item’s position in the menu. For example, a value of 1
corresponds to the first item in the list. If you want to change the selection in your code,
then change the Value property to another number between 1 and the number of items
in the menu.
For example, you can use the handles structure in GUIDE to access the pop-up menu
and change the Value property:
set(handles.popupmenu1,'Value',2)
This code is an example of a pop-up menu callback function in GUIDE. Associate this
function with the pop-up menu Callback property to make it execute when the end user
selects an item from the menu.
7-19
7 Programming a GUIDE App
When the user selects an item in the pop-up menu, the callback function performs the
following tasks:
• Gets all the items in the pop-up menu and stores them in the variable, items.
• Gets the numeric index of the selected item and stores it in the variable,
index_selected.
• Gets the value of the selected item and stores it in the variable, item_selected.
• Displays the selected item in the MATLAB Command Window.
Panel
Make the Panel Respond to Button Clicks
You can create a callback function that executes when the end user right-clicks or left-
clicks on the panel. If you are working in GUIDE, then right-click the panel in the layout
and select View Callbacks > ButtonDownFcn to create the callback function.
When the end user clicks on the panel, this function displays the text, 'Mouse button
was pressed', in the Command Window.
7-20
Callbacks for Specific Components
By default, GUIDE UIs cannot be resized, but you can override this behavior by selecting
Tools > GUI Options and setting Resize behavior to Proportional.
Programmatic UIs can be resized by default, and you can change this behavior by setting
the Resize property of the figure on or off.
When the UI window is resizable, the position of components in the window adjust as the
user resizes it. If you have a panel in your UI, then the panel’s size will change with the
window’s size. Use the panel’s SizeChangedFcn callback to make your app perform
specific tasks when the panel resizes.
If your UI contains nested panels, then they will resize from the inside-out (in child-to-
parent order).
Note To make the text inside a panel resize automatically, set the fontUnits property to
'normalized'.
Button Group
Button groups are similar to panels, but they also manage exclusive selection of radio
buttons and toggle buttons. When a button group contains multiple radio buttons or
toggle buttons, the button group allows the end user to select only one of them.
7-21
7 Programming a GUIDE App
Do not code callbacks for the individual buttons that are inside a button group. Instead,
use the button group’s SelectionChangedFcn callback to respond when the end user
selects a button.
When the end user selects a radio button or toggle button in the button group, this
function determines which button the user selected based on the button’s Tag property.
Then, it executes the code inside the appropriate case.
Note The button group’s SelectedObject property contains a handle to the button that
user selected. You can use this property elsewhere in your code to determine which
button the user selected.
Menu Item
The code in this section contains example callback functions that respond when the end
user selects Edit > Copy > To File in this menu.
7-22
Callbacks for Specific Components
% --------------------------------------------------------------------
function edit_menu_Callback(hObject, eventdata, handles)
% hObject handle to edit_menu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
display('Edit menu selected');
% --------------------------------------------------------------------
function copy_menu_item_Callback(hObject, eventdata, handles)
7-23
7 Programming a GUIDE App
% --------------------------------------------------------------------
function tofile_menu_item_Callback(hObject, eventdata, handles)
% hObject handle to tofile_menu_item (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename,path] = uiputfile('myfile.m','Save file name');
The function names might be different in your code, depending on the tag names you
specify in the GUIDE Menu Editor.
• When the end user selects the Edit menu, the edit_menu_Callback function
displays the text, 'Edit menu selected', in the MATLAB Command Window.
• When the end user hovers the mouse over the Copy menu item, the
copy_menu_item_Callback function displays the text, 'Copy menu item
selected', in the MATLAB Command Window.
• When the end user clicks and releases the mouse button on the To File menu item, the
tofile_menu_item_Callback function displays a dialog box that prompts the end
user to select a destination folder and file name.
When you create a cascading menu like this one, the intermediate menu items trigger
when the mouse hovers over them. The final, terminating, menu item triggers when the
mouse button releases over the menu item.
You can add a check mark next to a menu item to indicate that an option is enabled. In
GUIDE, you can select Check mark this item in the Menu Editor to make the menu item
checked by default. Each time the end user selects the menu item, the callback function
can turn the check on or off.
This code shows how to change the check mark next to a menu item.
7-24
Callbacks for Specific Components
if strcmp(get(hObject,'Checked'),'on')
set(hObject,'Checked','off');
else
set(hObject,'Checked','on');
end
The strcmp function compares two character vectors and returns true when they
match. In this case, it returns true when the menu item’s Checked property matches the
character vector, 'on'.
See “Create Menus for GUIDE Apps” on page 6-78 for more information about creating
menu items in GUIDE. See “Create Menus for Programmatic Apps” on page 9-38 for
more information about creating menu items programmatically.
Table
This code is an example of the table callback function, CellSelectionCallback.
Associate this function with the table CellSelectionCallback property to make it
execute when the end user selects cells in the table.
function uitable1_CellSelectionCallback(hObject, eventdata, handles)
% hObject handle to uitable1 (see GCBO)
% eventdata structure with the following fields
% Indices: row and column indices of the cell(s) currently selected
% handles structure with handles and user data (see GUIDATA)
data = get(hObject,'Data');
indices = eventdata.Indices;
r = indices(:,1);
c = indices(:,2);
linear_index = sub2ind(size(data),r,c);
selected_vals = data(linear_index);
selection_sum = sum(sum(selected_vals))
When the end user selects cells in the table, this function performs the following tasks:
• Gets all the values in the table and stores them in the variable, data.
• Gets the indices of the selected cells. These indices correspond to the rows and
columns in data.
• Converts the row and column indices into linear indices. The linear indices allow you
to select multiple elements in an array using one command.
• Gets the values that the end user selected and stores them in the variable,
selected_vals.
7-25
7 Programming a GUIDE App
• Sums all the selected values and displays the result in the Command Window.
When the end user finishes editing a table cell, this function gets all the values in the
table and calculates the sum of all the table values. The ColumnEditable property must
be set to true in at least one column to allow the end user to edit cells in the table. For
more information about creating tables and modifying their properties in GUIDE, see
“Add Components to the GUIDE Layout Area” on page 6-13.
Axes
The code in this section is an example of an axes ButtonDownFcn that triggers when the
end user clicks on the axes.
7-26
Callbacks for Specific Components
The coordinates of the pointer display in the MATLAB Command Window when the end
user clicks on the axes (but not when that user clicks on another graphics object parented
to the axes).
7-27
7 Programming a GUIDE App
Note Most MATLAB plotting functions clear the axes and reset a number of axes
properties, including the ButtonDownFcn, before plotting data. To create an interface
that lets the end user plot data interactively, consider providing a component such as a
push button to control plotting. Such components’ properties are unaffected by the
plotting functions. If you must use the axes ButtonDownFcn to plot data, then use
functions such as line, patch, and surface.
See Also
Related Examples
• “Write Callbacks in GUIDE” on page 7-2
• “Write Callbacks for Apps Created Programmatically” on page 10-5
7-28
Examples of GUIDE Apps
7-29
8
This example shows how to create a program that opens a modal dialog box when the
user clicks a button. The dialog box contains two buttons, and the user must choose one
of them. The program responds according to the user’s selection in the dialog box.
8-2
Modal Dialog Box in GUIDE
8-3
8 Examples of GUIDE UIs
On the Editor tab, in the Navigate section, click Go To, and then select
pushbutton1_Callback.
8-4
Modal Dialog Box in GUIDE
pos_size = get(handles.figure1,'Position');
When the user clicks the Close button in the closedlg window, the
pushbutton1_Callback function executes this command:
Recall that the modaldlg function is coded in the other program file, modaldlg.m.
That function displays a second window: the Confirm Close dialog box. The return
argument, user_response, is the user’s selection from that dialog box.
The switch command decides whether to close the first window (modaldlg) based on
the user’s selection.
9 Save your code by pressing Save in the Editor Toolstrip.
8-5
8 Examples of GUIDE UIs
3 Click one of the buttons in the Confirm Close dialog box. When you click one of the
buttons, modaldlg.m closes the Confirm Close dialog box and returns your selection
to the calling function (pushbutton1_Callback). Then, the switch command in
that function decides whether to close the remaining open window.
See Also
Related Examples
• “Create a Simple App Using GUIDE” on page 2-2
• “Dialog Boxes”
• “Write Callbacks in GUIDE” on page 7-2
8-6
GUIDE App With Parameters for Displaying Plots
Press the Plot button to see the graph of the function in the frequency and time domains.
8-7
8 Examples of GUIDE UIs
8-8
GUIDE App With Parameters for Displaying Plots
The f1_input_Callback function executes when the user changes the value in the f1
edit field. The f2_input_Callback function responds to changes in the f2 field, and it is
almost identical to the f1_input_Callback function. Both functions check for valid user
input. If the value in the edit field is invalid, the Plot button is disabled. Here is the code
for the f1_input_Callback function.
f1 = str2double(get(hObject,'String'));
if isnan(f1) || ~isreal(f1)
% Disable the Plot button and change its string to say why
set(handles.plot_button,'String','Cannot plot f1');
set(handles.plot_button,'Enable','off');
% Give the edit text box focus so user can correct the error
uicontrol(hObject);
else
% Enable the Plot button with its original name
set(handles.plot_button,'String','Plot');
set(handles.plot_button,'Enable','on');
end
t_input_Callback
The t_input_Callback function executes when the user changes the value in the t edit
field. This try block checks the value to make sure that it is numeric, that its length is
between 2 and 1000, and that the vector is monotonically increasing.
try
t = eval(get(handles.t_input,'String'));
if ~isnumeric(t)
% t is not a number
set(handles.plot_button,'String','t is not numeric')
elseif length(t) < 2
% t is not a vector
set(handles.plot_button,'String','t must be vector')
elseif length(t) > 1000
% t is too long a vector to plot clearly
set(handles.plot_button,'String','t is too long')
elseif min(diff(t)) < 0
% t is not monotonically increasing
set(handles.plot_button,'String','t must increase')
else
% Enable the Plot button with its original name
set(handles.plot_button,'String','Plot')
8-9
8 Examples of GUIDE UIs
set(handles.plot_button,'Enable','on')
return
end
catch EM
% Cannot evaluate expression user typed
set(handles.plot_button,'String','Cannot plot t');
uicontrol(hObject);
end
The catch block changes the label on the Plot button to indicate that an input value was
invalid. The uicontrol command sets the focus to the field that contains the erroneous
value.
plot_button_Callback
The plot_button_Callback function executes when the user clicks the Plot button.
First, the callback gets the values in the three edit fields:
f1 = str2double(get(handles.f1_input,'String'));
f2 = str2double(get(handles.f2_input,'String'));
t = eval(get(handles.t_input,'String'));
Then callback uses values of f1, f2, and t to sample the function in the time domain and
calculate the Fourier transform. Then, the two plots are updated:
See Also
Related Examples
• “Create a Simple App Using GUIDE” on page 2-2
8-10
See Also
8-11
8 Examples of GUIDE UIs
8-12
GUIDE App Containing Tables and Plots
8-13
8 Examples of GUIDE UIs
plot_type_Callback
The plot_type_Callback function executes when the user changes the selection in the
pop-up menu at the top of the window. The following statements get the currently
selected menu item and update the label above the axes.
index = get(hObject,'Value');
strlist = get(hObject,'String');
set(handles.uipanel3,'Title',strlist(index))
These commands get all 288 entries in the table and plot them in the top axes. The
refreshDisplays function is a locally defined function.
table = get(handles.data_table,'Data');
refreshDisplays(table, handles, 1);
These commands update the bottom plot and the statistical summary table if more than
10 entries are selected.
selection = handles.currSelection;
if length(selection) > 10
refreshDisplays(table(selection,:), handles, 2)
else
% Do nothing; insufficient observations for statistics
end
data_table_CellSelectionCallback
selection = eventdata.Indices(:,1);
These commands update the currSelection field of the handles structure so that the
user’s selection can be accessed from within other callbacks such as the
plot_type_Callback function.
handles.currSelection = selection;
guidata(hObject,handles);
Finally, refreshDisplays updates the bottom plot and the statistical summary table.
refreshDisplays(table(selection,:),handles,2);
8-14
See Also
See Also
Related Examples
• “Create a Simple App Using GUIDE” on page 2-2
• “Write Callbacks in GUIDE” on page 7-2
• “Share Data Among Callbacks” on page 11-2
8-15
8 Examples of GUIDE UIs
8-16
Interactive List Box App in GUIDE
Alternatively, you can call the lbox2 function in the Command Window with the 'dir'
name-value pair argument. The name-value pair argument allows you to list the contents
of any folder. For example, this command lists the files in the C:\ folder on a Windows®
system:
lbox2('dir','C:\')
8-17
8 Examples of GUIDE UIs
Note: Before you can call lbox2 in the Command Window, you must save the GUIDE files
in a folder on your MATLAB® path. To save the files, select File > Save As in GUIDE.
lbox2_OpeningFcn
The callback function lbox2_OpeningFcn executes just before the list box appears in
the UI for the first time. The following statements determine whether the user specified a
path argument to the lbox2 function.
if nargin == 3,
initial_dir = pwd;
elseif nargin > 4
if strcmpi(varargin{1},'dir')
if exist(varargin{2},'dir')
initial_dir = varargin{2};
8-18
Interactive List Box App in GUIDE
else
errordlg('Input must be a valid directory','Input Argument Error!')
return
end
else
errordlg('Unrecognized input argument','Input Argument Error!');
return;
end
end
listbox1_callback
The callback function listbox1_callback executes when the user clicks a list box item.
This statement, near the beginning of the function, returns true whenever the user
double-clicks an item in the list box:
if strcmp(get(handles.figure1,'SelectionType'),'open')
If that condition is true, then listbox1_callback determines which list box item the
user selected:
index_selected = get(handles.listbox1,'Value');
file_list = get(handles.listbox1,'String');
filename = file_list{index_selected};
The rest of the code in this callback function determines how to open the selected item
based on whether the item is a folder, FIG file, or another type of file:
if handles.is_dir(handles.sorted_index(index_selected))
cd (filename)
load_listbox(pwd,handles)
else
[path,name,ext] = fileparts(filename);
switch ext
case '.fig'
guide (filename)
otherwise
try
8-19
8 Examples of GUIDE UIs
open(filename)
catch ex
errordlg(...
ex.getReport('basic'),'File Type Error','modal')
end
end
end
See Also
Related Examples
• “Create a Simple App Using GUIDE” on page 2-2
• “Write Callbacks in GUIDE” on page 7-2
• “Share Data Among Callbacks” on page 11-2
8-20
Plot Workspace Variables in a GUIDE App
This example shows how to examine and run a prebuilt GUIDE app. The app contains a
list box that displays the variables in your MATLAB workspace. The button below the list
box refreshes the list. The three buttons on the right plot the selected variables using
different scales for the x and y axes.
8-21
8 Examples of GUIDE UIs
update_button_Callback
The update_button_Callback function executes when the user clicks the Update
Listbox button. It contains one command that calls another local function,
update_listbox. (That function is kept separate so it can be reused elsewhere in the
app.)
The update_listbox function executes the who command in the MATLAB workspace to
get the list of current variables. Then it sets the contents of the list box to that list of
variables.
vars = evalin('base','who');
set(handles.listbox1,'String',vars)
8-22
See Also
plot_button_Callback
The plot_button_Callback function executes when the user presses the Plot button.
The callbacks for the Semilogx and Semilogy buttons contain most of the same code.
First, the function calls the local function get_var_names, which returns the two
selected variables in the list.
[x,y] = get_var_names(handles);
Then it checks to make sure at least one variable is selected. If no variables are selected,
the callback returns and does not plot anything.
Finally, the plot command executes from within the base workspace.
try
evalin('base',['plot(',x,',',y,')'])
catch ex
errordlg(ex.getReport('basic'),...
'Error generating linear plot','modal')
end
See Also
Related Examples
• “Create a Simple App Using GUIDE” on page 2-2
• “Write Callbacks in GUIDE” on page 7-2
• “Share Data Among Callbacks” on page 11-2
8-23
8 Examples of GUIDE UIs
8-24
Automatically Refresh Plot in a GUIDE App
8-25
8 Examples of GUIDE UIs
ex_guide_timergui_OpeningFcn
The callback function for the timer is update_display, which is defined as a local
function.
update_display
The update_display function executes when the specified timer period elapses. The
function gets the values in the ZData property of the Surface object and adds random
noise to it. Then it updates the plot.
handles = guidata(hfigure);
Z = get(handles.surf,'ZData');
Z = Z + 0.1*randn(size(Z));
set(handles.surf,'ZData',Z);
periodsldr_Callback
The periodsldr_Callback function executes when the user moves the slider. It
calculates the timer period by getting the slider value and truncating it. Then it updates
the label below the slider and updates the period of the timer object.
% Read the slider value
period = get(handles.periodsldr,'Value');
% Truncate the value returned by the slider.
period = period - mod(period,.01);
% Set slider readout to show its value.
set(handles.slidervalue,'String',num2str(period))
% If timer is on, stop it, reset the period, and start it again.
if strcmp(get(handles.timer, 'Running'), 'on')
stop(handles.timer);
set(handles.timer,'Period',period)
start(handles.timer)
else % If timer is stopped, reset its period.
set(handles.timer,'Period',period)
end
8-26
See Also
startbtn_Callback
The startbtn_Callback function calls the start method of the timer object if the
timer is not already running.
stopbtn_Callback
The stopbtn_Callback function calls the stop method of the timer object if the timer
is currently running.
figure1_CloseRequestFcn
The figure1_CloseRequestFcn callback executes when the user closes the app. The
function stops the timer object if it is running, deletes the timer object, and then
deletes the figure window.
See Also
Related Examples
• “Timer Callback Functions”
• “Write Callbacks in GUIDE” on page 7-2
8-27
Create UIs Programmatically
• “Lay Out a UI Programmatically” on page 9-25
• “Create Menus for Programmatic Apps” on page 9-38
• “Create Toolbars for Programmatic Apps” on page 9-51
• “Create a Simple App Programmatically” on page 3-2
• “Write Callbacks for Apps Created Programmatically” on page 10-5
• “Callbacks for Specific Components” on page 7-12
• “Share Data Among Callbacks” on page 11-2
29
9
File Organization
Typically, the code file for an app has the following ordered sections. You can help to
maintain the structure by adding comments that name the sections when you first create
them.
File Template
This is a template you can use to create an app code file:
% Initialization tasks
9-2
See Also
% Initialization tasks
end
Save the file in your current folder or at a location that is on your MATLAB path.
myui
at the command line. Provide run-time arguments as appropriate. The file must reside on
your path or in your current folder.
When you execute the code, a fully functional copy of the UI displays on the screen. If the
file includes code to initialize the app and callbacks to service the components, you can
manipulate components that it contains.
See Also
Related Examples
• “Create a Simple App Programmatically” on page 3-2
9-3
9 Lay Out a Programmatic UI
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
9-4
Add Components to a Programmatic App
'Position',[50 20 60 40] specifies the location and size of the push button. In this
example, the push button is 60 pixels wide and 40 high. It is positioned 50 pixels from the
left of the figure and 20 pixels from the bottom.
Displaying an Icon on a Push Button
To add an icon to a push button, assign the button's CData property to be an m-by-n-by-3
array of RGB values that define a truecolor image.
Radio Button
f = figure;
r = uicontrol(f,'Style','radiobutton',...
'String','Indent nested functions.',...
'Value',1,'Position',[30 20 150 20]);
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group. If you have multiple radio buttons, you can manage their selection by
specifying the parent to be a button group. See “Button Groups” on page 9-18 for more
information.
9-5
9 Lay Out a Programmatic UI
'Value',1 selects the radio button by default. Set the Value property to be the value of
the Max property to select the radio button. Set the value to be the value of the Min
property to deselect the radio button. The default values of Max and Min are 1 and 0,
respectively.
'Position',[30 20 150 20] specifies the location and size of the radio button. In this
example, the radio button is 150 pixels wide and 20 high. It is positioned 30 pixels from
the left of the figure and 20 pixels from the bottom.
Toggle Button
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
The 'Value',0 deselects the toggle button by default. To select (raise) the toggle button,
set Value equal to the Max property. To deselect the toggle button, set Value equal to
the Min property. By default, Min = 0 and Max = 1.
9-6
Add Components to a Programmatic App
'Position',[30 20 100 30] specifies the location and size of the toggle button. In
this example, the toggle button is 100 pixels wide and 30 pixels high. It is positioned 30
pixels from the left of the figure and 20 pixels from the bottom.
Note You can also display an icon on a toggle button. See “Displaying an Icon on a Push
Button” on page 9-5 for more information.
Check Box
f = figure;
c = uicontrol(f,'Style','checkbox',...
'String','Display file extension',...
'Value',1,'Position',[30 20 130 20]);
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
The next pair, 'String','Display file extension' puts a text label on the check
box.
The Value property specifies whether the box is checked. Set Value to the value of the
Max property (default is 1) to create the component with the box checked. Set Value to
Min (default is 0) to leave the box unchecked. Correspondingly, when the user clicks the
9-7
9 Lay Out a Programmatic UI
check box, MATLAB sets Value to Max when the user checks the box and to Min when
the user unchecks it.
The Position property specifies the location and size of the check box. In this example,
the check box is 130 pixels wide and 20 high. It is positioned 30 pixels from the left of the
figure and 20 pixels from the bottom.
Slider
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
'Min',0 and 'Max',100 specify the range of the slider to be [0, 100]. The Min property
must be less than Max.
'Value',25 sets the default slider position to 25. The number you specify for this
property must be within the range, [Min, Max].
9-8
Add Components to a Programmatic App
'SliderStep',[0.05 0.2] specifies the fractional amount that the thumb moves when
the user clicks the arrow buttons or the slider trough (also called the channel). In this
case, the slider’s thumb position changes by the smaller amount (5 percent) when the
user clicks an arrow button. It changes by the larger amount (20 percent) when the user
clicks the trough.
As major_step increases, the thumb grows longer. When major_step is 1, the thumb is
half as long as the trough. When major_step is greater than 1, the thumb continues to
grow, slowly approaching the full length of the trough. When a slider serves as a scroll
bar, you can uses this behavior to indicate how much of the document is currently visible
by changing the value of major_step.
'Position',[30 20 150 30] specifies the location and size of the slider. In this
example, the slider is 150 pixels wide and 30 high. It is positioned 30 pixels from the left
of the figure and 20 pixels from the bottom.
Note On Mac platforms, the height of a horizontal slider is constrained. If the height you
set in the Position property exceeds this constraint, the displayed height of the slider is
the maximum allowed by the system. However, the value of the Position property does
not change to reflect this constraint.
Static Text
9-9
9 Lay Out a Programmatic UI
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
The name-value pair arguments, 'Style','text' specify the uicontrol to be static text.
'String','Select a set' specifies the text that displays. If you specify a component
width that is too small to accommodate all of the text, MATLAB wraps the text.
'Position',[30 50 130 30] specifies the location and size of the static text. In this
example, the static text is 130 pixels wide and 20 high. It is positioned 30 pixels from the
left of the figure and 50 pixels from the bottom.
f = figure;
txtbox = uicontrol(f,'Style','edit',...
'String','Enter your name here.',...
'Position',[30 50 130 20]);
9-10
Add Components to a Programmatic App
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
The name-value pair arguments, 'Style','edit', specify the style of the uicontrol to
be an editable text field.
The next pair, 'Position',[30 50 130 20] specifies the location and size of the text
field. In this example, the text field is 130 pixels wide and 20 pixels high. It is positioned
30 pixels from the left of the figure and 50 pixels from the bottom.
To enable multiple-line input, the value of Max - Min must be greater than 1, as in the
following statement.
txtbox = uicontrol(f,'Style','edit',...
'String','Enter your name and address here.',...
'Max',2,'Min',0,...
'Position',[30 20 130 80]);
9-11
9 Lay Out a Programmatic UI
If the value of Max - Min is less than or equal to 1, the editable text field allows only a
single line of input. If the width of the text field is too narrow for the text, MATLAB
displays only part of the text. The user can use the arrow keys to move the cursor over
the entire line of text.
Pop-Up Menu
f = figure;
pm = uicontrol(f,'Style','popupmenu',...
'String',{'one','two','three','four'},...
'Value',1,'Position',[30 80 130 20]);
9-12
Add Components to a Programmatic App
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
'Value',1 sets the index of the item that is selected by default. Set Value to a scalar
that indicates the index of the selected item. A value of 1 selects the first item.
'Position',[30 80 130 20] specifies the location and size of the pop-up menu. In
this example, the pop-up menu is 130 pixels wide. It is positioned 30 pixels from the left
of the figure and 80 pixels from the bottom. The height of a pop-up menu is determined by
the font size; the height you set in the position vector is ignored.
List Box
9-13
9 Lay Out a Programmatic UI
'String',{'one','two','three','four'},...
'Position',[30 20 130 80],'Value',1);
The first uicontrol argument, f, specifies the parent container. In this case, the parent
is a figure, but you can also specify the parent to be any container, such as a panel or
button group.
'Position',[30 20 130 80] specifies the location and size of the list box. In this
example, the list box is 130 pixels wide and 80 high. It is positioned 30 pixels from the left
of the figure and 20 pixels from the bottom.
The final pair of arguments, Value,1 sets the list selection to the first item in the list. To
select a single item, set the Value property to be a scalar that indicates the position of
the item in the list.
To select more than one item, set the Value property to be a vector of values. To enable
your users to select multiple items, set the values of the Min and Max properties such that
Max - Min is greater than 1. Here is a list box that allows multiple selections and has
two items selected initially:
9-14
Add Components to a Programmatic App
lb = uicontrol(f,'Style','listbox',...
'String',{'one','two','three','four'},...
'Max',2,'Min',0,'Value',[1 3],...
'Position',[30 20 130 80]);
• Set the Max and Min properties such that Max - Min is greater than 1.
• Set the Value property to an empty matrix [].
If the list box is not large enough to display all list entries, you can set the ListBoxTop
property to the index of the item you want to appear at the top when the component is
created.
Tables
This code creates a table and populates it with the values returned by magic(5).
f = figure;
tb = uitable(f,'Data',magic(5));
The first uitable argument, f, specifies the parent container. In this case, the parent is a
figure, but you can also specify the parent to be any container, such as a panel or button
group.
9-15
9 Lay Out a Programmatic UI
The name-value pair arguments, 'Data',magic(5), specifies the table data. In this
case, the data is the 5-by-5 matrix returned by the magic(5) command.
You can adjust the width and height of the table to accommodate the extent of the data.
The uitable’s Position property controls the outer bounds of the table, and the Extent
property indicates the extent of the data. Set the last two values in the Position
property to the corresponding values in the Extent property:
tb.Position(3) = tb.Extent(3);
tb.Position(4) = tb.Extent(4);
You can change several other characteristics of the table by setting certain properties:
• To control the user’s ability to edit the table cells, set the ColumnEditable property.
• To make your application respond when the user edits a cell, define a
CellEditCallback function.
• To add or change row striping, set the RowStriping property.
• To specify row and column names, set the RowName and ColumnName properties.
• To format the data in the table, set the ColumnFormat property.
If you are building an app using GUIDE, you can set many of the uitable properties using
the Table Property Editor. For more information, see “Create a Table” on page 6-50.
Panels
This code creates a panel:
f = figure;
p = uipanel(f,'Title','My Panel',...
'Position',[.25 .1 .5 .8]);
9-16
Add Components to a Programmatic App
The first argument passed to uipanel, f, specifies the parent container. In this case, the
parent is a figure, but you can also specify the parent to be any container, such as another
panel or a button group.
'Position',[.25 .1 .5 .8] specifies the location and size of the panel as a fraction
of the parent container. In this case, the panel is 50 percent of the width of the figure and
80 percent of its height. The left edge of the panel is located at 25 percent of the figure’s
width from the left. The bottom of the panel is located 10 percent of the figure’s height
from the bottom. If the figure is resized, the panel retains its original proportions.
The following commands add two push buttons to the panel. Setting the Units property
to 'normalized' causes the Position values to be interpreted as fractions of the
parent panel. Normalized units allow the buttons to retain their original proportions when
the panel is resized.
9-17
9 Lay Out a Programmatic UI
b1 = uicontrol(p,'Style','pushbutton','String','Button 1',...
'Units','normalized',...
'Position',[.1 .55 .8 .3]);
b2 = uicontrol(p,'Style','pushbutton','String','Button 2',...
'Units','normalized',...
'Position',[.1 .15 .8 .3]);
Button Groups
This code creates a button group:
f = figure;
bg = uibuttongroup(f,'Title','My Button Group',...
'Position',[.1 .2 .8 .6]);
9-18
Add Components to a Programmatic App
The first argument passed to uibuttongroup, f, specifies the parent container. In this
case, the parent is a figure, but you can also specify the parent to be any container, such
as a panel or another button group.
'Position',[.1 .2 .8 .6] specifies the location and size of the button group as a
fraction of the parent container. In this case, the button group is 80 percent of the width
of the figure and 60 percent of its height. The left edge of the button group is located at
10 percent of the figure’s width from the left. The bottom of the button group is located
20 percent of the figure’s height from the bottom. If the figure is resized, the button
group retains its original proportions.
The following commands add two radio buttons to the button group. Setting the Units
property to 'normalized' causes the Position values to be interpreted as fractions of
the parent panel. Normalized units allow the buttons to retain their original relative
positions when the button group is resized.
9-19
9 Lay Out a Programmatic UI
rb1 = uicontrol(bg,'Style','radiobutton','String','Red',...
'Units','normalized',...
'Position',[.1 .6 .3 .2]);
rb2 = uicontrol(bg,'Style','radiobutton','String','Blue',...
'Units','normalized',...
'Position',[.1 .2 .3 .2]);
By default, the first radio button added to the uibuttongroup is selected. To override this
default, set any other radio button’s Value property to its Max property value.
Button groups manage the selection of radio buttons and toggle buttons by allowing only
one button to be selected within the group. You can determine the currently selected
button by querying the uibuttongroup’s SelectedObject property.
Axes
This code creates an axes in a figure:
9-20
Add Components to a Programmatic App
f = figure;
ax = axes('Parent',f,'Position',[.15 .15 .7 .7]);
The first two arguments passed to the axes function, 'Parent',f specify the parent
container. In this case, the parent is a figure, but you can also specify the parent to be any
container, such as a panel or button group.
'Position',[.15 .15 .7 .7] specifies the location and size of the axes as a fraction
of the parent figure. In this case, the axes is 70 percent of the width of the figure and 70
percent of its height. The left edge of the axes is located at 15 percent of the figure’s
width from the left. The bottom of the axes is located 15 percent of the figure’s height
from the bottom. If the figure is resized, the axes retains its original proportions.
9-21
9 Lay Out a Programmatic UI
Data graphing functions, such as plot, image, and scatter, reset axes properties
before they draw into an axes. This can be a problem when you want to maintain
consistency of axes limits, ticks, colors, and font characteristics in a UI.
The default value of the NextPlot axes property, 'replace' allows the graphing
functions to reset many property values. In addition, the 'replace' property value
allows MATLAB to remove all callbacks from the axes whenever a graph is plotted. If you
place an axes in a UI, consider setting the NextPlot property to 'replacechildren'.
You might need to set this property prior to changing the contents of an axes:
ax.NextPlot = 'replacechildren';
ActiveX Controls
ActiveX components enable you to display ActiveX controls in your UI. They are available
only on the Microsoft Windows platform.
An ActiveX control can be the child only of a figure. It cannot be the child of a panel or
button group.
See “Creating an ActiveX Control” about adding an ActiveX control to a figure. See
“Create COM Objects” for general information about ActiveX controls.
Use the uisetfont function to display a dialog that allows you to choose a font, style,
and size all at once:
myfont = uisetfont
9-22
Add Components to a Programmatic App
You can use this information to set font characteristics of a component in the UI:
btn = uicontrol;
btn.FontName = myfont.FontName;
btn.FontSize = myfont.FontSize;
9-23
9 Lay Out a Programmatic UI
set(btn,myfont);
See Also
Related Examples
• “Callbacks for Specific Components” on page 7-12
• “Write Callbacks for Apps Created Programmatically” on page 10-5
9-24
Lay Out a UI Programmatically
The area inside the figure, which contains the UI components, is called the drawable
area. The drawable area excludes the figure borders, title bar, menu bar, and tool bars.
You can control the location and size of the drawable area by setting the Position
property of the figure as a four-element row vector. The first two elements of this vector
specify the location. The last two elements specify the size. By default, the figure’s
Position values are in pixels.
This command creates a figure and sets the Position value. The left edge of the
drawable area is 258 pixels from the left side of the screen. Its bottom edge is 132 pixels
up from the bottom of the screen. Its size is 560 pixels wide by 420 pixels high:
9-25
9 Lay Out a Programmatic UI
You can query or change the outer bounds of the figure by using the OuterPosition
property. The region enclosed by the outer bounds of the figure includes the figure
borders, title bar, menu bar, and tool bars. Like the Position property, the
OuterPosition is a four element row vector:
f.OuterPosition
9-26
Lay Out a UI Programmatically
ans =
The left outer edge of this figure is 250 pixels from the left side of the screen. Its bottom
outer edge is 124 pixels up from the bottom of the screen. The area enclosed by the outer
bounds of the figure is 576 pixels wide by 512 pixels high.
9-27
9 Lay Out a Programmatic UI
f.Position
ans =
ans =
Units of Measure
The default units associated with the Position property depend on the component you
are placing. However, you can change the Units property to lay out your UI in the units
of your choice. There are six different units of measure to choose from: inches,
centimeters, normalized, points, pixels, and characters.
Always specify Units before Position for the most predictable results.
f = figure('Units','inches','Position',[4 3 6 5]);
Your choice of units can affect the appearance and resizing behavior of the UI:
• If you want the UI components to scale proportionally with the figure when the user
resizes the figure, set the Units property of the components to 'normalized'.
• UI Components do not scale proportionally inside the figure when their Units
property is set to 'inches', 'centimeters', 'points', 'pixels', or
'characters'.
• If you are developing a cross-platform UI, then set the Units property to 'points'
or 'characters' to make the layout consistent across all platforms.
9-28
Lay Out a UI Programmatically
Here is the code for a simple app containing an axes and a button. To see how it works,
copy and paste this code into the editor and run it.
function myui
% Add the UI components
hs = addcomponents;
function hs = addcomponents
% add components, save handles in a struct
hs.fig = figure('Visible','off',...
'Resize','off',...
'Tag','fig');
hs.btn = uicontrol(hs.fig,'Position',[10 340 70 30],...
'String','Plot Sine',...
'Tag','button',...
'Callback',@plotsine);
hs.ax = axes('Parent',hs.fig,...
'Position',[0.20 0.13 0.71 0.75],...
'Tag','ax');
end
function plotsine(hObject,event)
theta = 0:pi/64:6*pi;
y = sin(theta);
plot(hs.ax,theta,y);
end
end
• The main function, myui, calls the addcomponents function. The addcomponents
function returns a structure, hs, containing the handles to all the UI components.
• The addcomponents function creates a figure, an axes, and a button, each with
specific Position values.
• Notice that the Resize property of the figure is 'off'. This value disables the
resizing capability of the figure.
• Notice that the Visible property of the figure is 'off' inside the
addcomponents function. The value changes to 'on' after addcomponents
9-29
9 Lay Out a Programmatic UI
returns to the calling function. Doing this delays the figure display until after
MATLAB adds all the components. Thus, the resulting UI has a clean appearance
when it starts up.
• The plotsine function plots the sine function inside the axes when the user clicks the
button.
If your UI has another container, such as a uipanel or uibuttongroup, you can manage the
layout of the container’s child components in a separate callback function that you assign
to the SizeChangedFcn property.
9-30
Lay Out a UI Programmatically
Note Typically, the drawable area changes at the same time the outer bounds change.
However, adding or removing menu bars or tool bars to a figure causes the outer bounds
to change while the drawable area remains constant. Therefore, the SizeChangedFcn
callback does not execute when you add or remove menu bars or tool bars.
This app is a resizable version of the simple app defined in “Example of a Simple Layout”
on page 9-29. This code includes a figure SizeChangedFcn callback called resizeui.
The resizeui function calculates new Position values for the button and axes when
the user resizes the window. The button appears to be stationary when the user resizes
the window. The axes scales with the figure.
function myui
% Add the UI components
hs = addcomponents;
function hs = addcomponents
% Add components, save handles in a struct
hs.fig = figure('Visible','off',...
'Tag','fig',...
'SizeChangedFcn',@resizeui);
hs.btn = uicontrol(hs.fig,'String',...
'Plot Sine',...
'Callback',@plotsine,...
'Tag','button');
hs.ax = axes('Parent',hs.fig,...
'Units','pixels',...
'Tag','ax');
end
function plotsine(hObject,event)
theta = 0:pi/64:6*pi;
y = sin(theta);
9-31
9 Lay Out a Programmatic UI
plot(hs.ax,theta,y);
end
function resizeui(hObject,event)
The resizeui function sets the location and size of the button and axes whenever the
user resizes the window:
• The button height, width, and left edge stay the same when the window resizes.
• The bottom edge of the button, bbottomedge, allows 50 pixels of space between the
top of the figure and the top of the button.
• The value of the axes height, axheight, is 75% of the available height in the figure.
• The value of the axes bottom edge, axbottomedge, allows 30 pixels of space between
the top of the figure and the top of the axes. In this calculation, the max function limits
this value to nonnegative values.
• The value of the axes width, axwidth, allows 50 pixels of space between the right side
of the axes and the right edge of the figure. In this calculation, the max function limits
this value to nonnegative values.
Notice that all the layout code is inside the resizeui function. It is a good practice to
put all the layout code inside the SizeChangedFcn callback to ensure the most accurate
results.
9-32
See Also
Also, it is important to delay the display of the entire UI window until after all the
variables that a SizeChangedFcn callback uses are defined. Doing so can prevent the
SizeChangedFcn callback from returning an error. To delay the display of the window,
set the Visible property of the figure to 'off'. After you define all the variables that
your SizeChangedFcn callback uses, set the Visible property to 'on'.
• Axes and other graphics objects appear behind other components. UI components and
containers (uipanels, uibuttongroups, and uitabs) appear in front of them.
• UI components and containers appear in the order in which you create them. New
components appear in front of existing components.
You can change the stacking order at any time, but there are some restrictions. Axes and
other graphics objects can stack in any order with respect to each other. However, axes
and other graphics objects cannot stack in front of UI components and containers. They
always appear behind UI components and containers.
You can work around this restriction by grouping graphics objects into separate
containers. Then you can stack those containers in any order. To group a graphics object
into a container, set its Parent property to be that container. For example, you can group
an axes into a uipanel by setting the Parent property of the axes to be the uipanel.
The Children property of a uipanel, uibuttongroup, or uitab lists the child objects inside
the container according to their stacking order.
See Also
Related Examples
• “DPI-Aware Behavior in MATLAB” on page 9-58
9-33
9 Lay Out a Programmatic UI
Tab order is determined separately for the children of each parent. For example, child
components of the figure window have their own tab order. Child components of each
panel or button group also have their own tab order.
If, in tabbing through the components at one level, a user tabs to a panel or button group,
then the tabbing sequences through the components of the panel or button group before
returning to the level from which the panel or button group was reached. For example, if
a figure window contains a panel that contains three push buttons and the user tabs to
the panel, then the tabbing sequences through the three push buttons before returning to
the figure.
Note You cannot tab to axes and static text components. You cannot determine
programmatically which component has focus.
The following code creates a UI that contains a pop-up menu with a static text label, a
panel with three push buttons, and an axes.
9-34
Customize Tabbing Behavior in a Programmatic App
You can obtain the default tab order for a figure, panel, or button group by looking at its
Children property. For the example, this command gets the children of the uipanel, ph.
ch = ph.Children
ch =
9-35
9 Lay Out a Programmatic UI
UIControl (Surf)
UIControl (Mesh)
UIControl (Contour)
The default tab order is the reverse of the child order: Contour, then Mesh, then Surf.
Note Displaying the children in this way shows only those children that have their
HandleVisibility property set to 'on'. Use allchild to retrieve children regardless
of their handle visibility.
In this example, the default order is pop-up menu followed by the panel's Contour,
Mesh, and Surf push buttons (in that order), and then back to the pop-up menu. You
cannot tab to the axes component or the static text component.
Try modifying the code to create the pop-up menu following the creation of the Contour
push button and before the Mesh push button. Now execute the code to run the app and
tab through the components. This code change does not alter the default tab order. This is
because the pop-up menu does not have the same parent as the push buttons. The figure
is the parent of the panel and the pop-up menu.
ch = ph.Children
ch =
UIControl (Surf)
UIControl (Mesh)
UIControl (Contour)
Next, call the uistack function to change the tab order of buttons. This code moves the
Mesh button up one level, making it the last item in the tab order.
uistack(ch(2),'up',1);
9-36
Customize Tabbing Behavior in a Programmatic App
The tab order of the three buttons is now Contour, then Surf, then Mesh.
ph.Children
ans =
UIControl (Mesh)
UIControl (Surf)
UIControl (Contour)
Note Tab order also affects the stacking order of components. If components overlap,
those that appear higher in the child order, display on top of those that appear lower in
the order.
9-37
9 Lay Out a Programmatic UI
mh = uimenu(parent,'PropertyName',PropertyValue,...)
Where mh is the handle of the resulting menu or menu item. See the uimenu reference
page for other valid syntaxes.
These topics discuss use of the MATLAB standard menu bar menus and describe
commonly used menu properties and offer some simple examples.
Displaying the standard menu bar menus is optional. This figure’s menu bar contains the
standard menus.
9-38
Create Menus for Programmatic Apps
If you use the standard menu bar menus, any menus you create are added to it. If you
choose not to display the standard menu bar menus, the menu bar contains only the
menus that you create. If you display no standard menus and you create no menus, the
menu bar itself does not display.
Use the figure MenuBar property to display or hide the MATLAB standard menu bar
shown in the preceding figure. Set MenuBar to figure (the default) to display the
standard menus. Set MenuBar to none to hide them.
fh.MenuBar = 'figure'; % Display standard menu bar menus.
fh.MenuBar = 'none'; % Hide standard menu bar menus.
When you customize the menu bar or toolbar, you can control the display of the window's
docking controls by setting the DockControls property. You might not need menus for
your app, but if you want the user to be able to dock or undock the window, it must
9-39
9 Lay Out a Programmatic UI
contain a menu bar or a toolbar. This is because docking is controlled by the docking icon,
a small curved arrow near the upper-right corner of the menu bar or the toolbar, as the
following illustration shows.
Figure windows with a standard menu bar also have a Desktop menu from which the
user can dock and undock them.
To display the docking arrow and the Desktop > Dock Figure menu item, the figure
property DockControls must be set to 'on'. You can set this property in the Property
Inspector. In addition, the MenuBar and/or ToolBar figure properties must be set to
'on' to display docking controls.
The WindowStyle figure property also affects docking behavior. The default is
'normal', but if you change it to 'docked', then the following applies:
• The UI opens docked in the desktop when you run the app.
• The DockControls property is set to 'on' and cannot be turned off until
WindowStyle is no longer set to 'docked'.
• If you undock a UI created with WindowStyle set to 'docked', the window will have
not have a docking arrow unless the figure displays a menu bar or a toolbar. When the
window has no docking arrow, users can undock it from the desktop, but will be
unable to redock it.
To summarize, you can display docking controls with the DockControls property as long
as it is not in conflict with the figure's WindowStyle property.
Note Modal dialogs (figures with the WindowStyle property set to 'modal') cannot
have menu bars, toolbars, or docking controls.
9-40
Create Menus for Programmatic Apps
For more information, see the DockControls, MenuBar, ToolBar, and WindowStyle
property descriptions on the Figure page.
The following statements create a menu bar menu with two menu items.
mh = uimenu(fh,'Text','My menu');
eh1 = uimenu(mh,'Text','Item 1');
eh2 = uimenu(mh,'Text','Item 2','Checked','on');
The Text property specifies the text that appears in the menu.
The Checked property specifies that this item is displayed with a check next to it when
the menu is created.
If your UI displays the standard menu bar, the new menu is added to it.
9-41
9 Lay Out a Programmatic UI
If your UI does not display the standard menu bar, MATLAB creates a menu bar if none
exists and then adds the menu to it.
9-42
Create Menus for Programmatic Apps
This command adds a separator line preceding the second menu item.
eh2.Separator = 'on';
9-43
9 Lay Out a Programmatic UI
The following statements add two menu subitems to Item 1, assign each subitem a
keyboard accelerator, and disable the first subitem.
9-44
Create Menus for Programmatic Apps
The Accelerator property adds keyboard accelerators to the menu items. Some
accelerators may be used for other purposes on your system and other actions may result.
The Enable property disables the first subitem Choice 1 so a user cannot select it when
the menu is first created. The item appears dimmed.
Note After you have created all menu items, set their HandleVisibility properties
off by executing the following statements:
menuhandles = findall(figurehandle,'type','uimenu');
menuhandles.HandleVisibility = 'off';
See the section, “Menu Item” on page 7-22, for information about programming menu
items.
9-45
9 Lay Out a Programmatic UI
Use the uicontextmenu function to create a context menu object. The syntax is
handle = uicontextmenu('PropertyName',PropertyValue,...)
The parent of a context menu must always be a figure. Use the Parent property to
specify the parent of a uicontextmenu. If you do not specify the Parent property, the
parent is the current figure as specified by the root CurrentFigure property.
The following code creates a figure and a context menu whose parent is the figure. At this
point, the figure is visible, but not the menu.
fh = figure('Position',[300 300 400 225]);
cmenu = uicontextmenu('Parent',fh,'Position',[10 215]);
Note “Force Display of the Context Menu” on page 9-49 explains the use of the
Position property.
Use the uimenu function to add items to the context menu. The items appear on the menu
in the order in which you add them. The following code adds three items to the context
menu created above.
mh1 = uimenu(cmenu,'Text','Item 1');
mh2 = uimenu(cmenu,'Text','Item 2');
mh3 = uimenu(cmenu,'Text','Item 3');
You can specify any applicable Uimenu when you define the context menu items. See the
uimenu reference page and “Add Menu Bar Menus” on page 9-38 for information about
9-46
Create Menus for Programmatic Apps
using uimenu to create menu items. Note that context menus do not have an
Accelerator property.
Note After you have created the context menu and all its items, set their
HandleVisibility properties to 'off' by executing the following statements:
cmenuhandles = findall(figurehandle,'type','uicontextmenu');
cmenuhandles.HandleVisibility = 'off';
menuitemhandles = findall(cmenuhandles,'type','uimenu');
menuitemhandles.HandleVisibility = 'off';
You can associate a context menu with the figure itself and with all components that have
a UIContextMenu property. This includes axes, panel, button group, all user interface
controls (uicontrols).
This code adds a panel and an axes to the figure. The panel contains a single push button.
ph = uipanel('Parent',fh,'Units','pixels',...
'Position',[20 40 150 150]);
bh1 = uicontrol(ph,'String','Button 1',...
'Position',[20 20 60 40]);
ah = axes('Parent',fh,'Units','pixels',...
'Position',[220 40 150 150]);
9-47
9 Lay Out a Programmatic UI
This code associates the context menu with the figure and with the axes by setting the
UIContextMenu property of the figure and the axes to the handle cmenu of the context
menu.
Right-click on the figure or on the axes. The context menu appears with its upper-left
corner at the location you clicked. Right-click on the panel or its push button. The context
menu does not appear.
9-48
Create Menus for Programmatic Apps
If you set the context menu Visible property on, the context menu is displayed at the
location specified by the Position property, without the user taking any action. In this
example, the context menu Position property is [10 215].
cmenu.Visible = 'on';
The context menu displays 10 pixels from the left of the figure and 215 pixels from the
bottom.
9-49
9 Lay Out a Programmatic UI
If you set the context menu Visible property to off, or if the user clicks outside the
context menu, the context menu disappears.
See Also
Menu | uimenu
Related Examples
• “Create Toolbars for Programmatic Apps” on page 9-51
9-50
Create Toolbars for Programmatic Apps
Syntaxes for the uitoolbar, uipushtool, and uitoggletool functions include the
following:
tbh = uitoolbar(fh,'PropertyName',PropertyValue,...)
pth = uipushtool(tnh,'PropertyName',PropertyValue,...)
tth = uitoggletool(tbh,'PropertyName',PropertyValue,...)
The output arguments, tbh, pth, and tth are the handles, respectively, of the resulting
toolbar, push tool, and toggle tool. See the uitoolbar, uipushtool, and
uitoggletool reference pages for other valid syntaxes.
Subsequent topics describe commonly used properties of toolbars and toolbar tools, offer
a simple example, and discuss use of the MATLAB standard toolbar:
9-51
9 Lay Out a Programmatic UI
For a complete list of properties and for more information about the properties listed in
the table, see the Uitoolbar, Uipushtool, and Uitoggletool.
Toolbars
The following statements add a toolbar to a figure, and then add a push tool and a toggle
tool to the toolbar. By default, the tools are added to the toolbar, from left to right, in the
order they are created.
9-52
Create Toolbars for Programmatic Apps
'HandleVisibility','off');
% Add a toggle tool to the toolbar
img2 = rand(16,16,3);
tth = uitoggletool(tbh,'CData',img2,'Separator','on',...
'Tooltip','Your toggle tool',...
'HandleVisibility','off');
CData is a 16-by-16-by-3 array of values between 0 and 1. It defines the truecolor image
that is displayed on the tool. If your image is larger than 16 pixels in either dimension, it
may be clipped or cause other undesirable effects. If the array is clipped, only the center
16-by-16 part of the array is used.
Note See the ind2rgb reference page for information on converting a matrix X and
corresponding colormap, i.e., an (X, MAP) image, to RGB (truecolor) format.
9-53
9 Lay Out a Programmatic UI
Tooltip specifies the tooltips for the push tool and the toggle tool as My push tool
and Your toggle tool, respectively.
In this example, setting the toggle tool Separator property to on creates a dividing line
to the left of the toggle tool.
You can change the order of the tools by modifying the child vector of the parent toolbar.
For this example, execute the following code to reverse the order of the tools.
oldOrder = allchild(tbh);
newOrder = flipud(oldOrder);
tbh.Children = newOrder;
This code uses flipud because the Children property is a column vector.
Use the delete function to remove a tool from the toolbar. The following statement
removes the toggle tool from the toolbar. The toggle tool handle is tth.
delete(tth)
9-54
Create Toolbars for Programmatic Apps
If necessary, you can use the findall function to determine the handles of the tools on a
particular toolbar.
Note After you have created a toolbar and its tools, set their HandleVisibility
properties off by executing statements similar to the following:
toolbarhandle.HandleVisibility = 'off';
toolhandles = toolbarhandle.Children;
toolhandles.HandleVisibility = 'off';
9-55
9 Lay Out a Programmatic UI
Use the figure ToolBar property to display or hide the standard toolbar. Set ToolBar to
'figure' to display the standard toolbar. Set ToolBar to 'none' to hide it.
The default ToolBar value is 'auto', which uses the MenuBar property value.
Once you have the handle of the standard toolbar, you can add tools, delete tools, and
change the order of the tools.
Add a tool the same way you would add it to a custom toolbar. This code gets the handle
of the standard toolbar and adds a toggle tool to it.
tbh = findall(fh,'Type','uitoolbar');
tth = uitoggletool(tbh,'CData',rand(20,20,3),...
'Separator','on',...
'HandleVisibility','off');
To remove a tool from the standard toolbar, determine the handle of the tool to be
removed, and then use the delete function to remove it. The following code deletes the
toggle tool that was added to the standard toolbar above.
delete(tth)
If necessary, you can use the findall function to determine the handles of the tools on
the standard toolbar.
9-56
See Also
See Also
uipushtool | uitoggletool | uitoolbar
Related Examples
• “Create Menus for Programmatic Apps” on page 9-38
9-57
9 Lay Out a Programmatic UI
Starting in R2015b, MATLAB is DPI-aware, which means that it takes advantage of your
full system resolution to draw graphical elements (fonts, UIs, and graphics). Graphical
elements appear sharp and consistent in size on these high-DPI systems:
• Windows systems in which the display dots-per-inch (DPI) value is set higher than 96
• Macintosh systems with Apple Retina displays
Previously, MATLAB allowed some operating systems to scale graphical elements. That
scaling helped to maintain consistent appearance and functionality, but it also introduced
undesirable effects. Graphical elements often looked blurry, and the size of those
elements was sometimes inconsistent.
Visual Appearance
Here are the visual effects you might notice on high-DPI systems:
• The MATLAB desktop, graphics, fonts, and most UI components look sharp and render
with full graphical detail on Macintosh and Windows systems.
9-58
DPI-Aware Behavior in MATLAB
• When you create a graphics or UI object, and specify the Units as 'pixels', the size
of that object is now consistent with the size of other objects. For example, the size of
a push button (specified in pixels) is now consistent with the size of the text on that
push button (specified in points).
• Elements in the MATLAB Toolstrip look sharper than in previous releases. However,
icons in the Toolstrip might still look slightly blurry on some systems.
• On Windows systems, the MATLAB Toolstrip might appear larger than in previous
releases.
9-59
9 Lay Out a Programmatic UI
• On Windows systems, the size of the Command Window fonts and Editor fonts might
be larger than in previous releases. In particular, you might see a difference if you
have nondefault font sizes selected in MATLAB preferences. You might need to adjust
those font sizes to make them look smaller.
• You might see differences on multiple-display systems that include a combination of
different displays (for example, some, but not all of the displays are high-DPI).
Graphical elements might look different across displays on those systems.
Units Property
When you set the Units property of a graphics or UI object to 'pixels', the size of each
pixel is now device-independent on Windows and Macintosh systems:
Your existing graphics and UI code will continue to function properly with the new pixel
size. Keep in mind that specifying (or querying) the size and location of an object in pixels
might not correspond to the actual pixels on your screen.
For example, each screen pixel on a 192-DPI Windows system is 1/192nd of an inch. In
this case, twice as many screen pixels cover the same linear distance as the device-
independent pixels do. If you create a figure, and specify its size to be 500-by-400 pixels,
MATLAB reports the size to be 500-by-400 in the Position property. However, the
display uses 1000-by-800 screen pixels to cover the same graphical region.
Note Starting in R2015b, MATLAB might report the size and location of objects as
fractional values (in pixel units) more frequently than in previous releases. For example,
your code might report fractional values in the Position property of a figure, whereas
previous releases reported whole numbers for that same figure.
9-60
DPI-Aware Behavior in MATLAB
The ScreenSize property of the root object might not match the display size reported by
high-DPI Windows systems. Specifically, the values do not match when the Units
property of the root object is set to 'pixels'. MATLAB reports the value of the
ScreenSize property based on device-independent pixels, not the size of the actual
pixels on the screen.
Also, you cannot set or query the default value of the ScreenPixelsPerInch property.
These commands now return an error:
get(groot,'DefaultRootScreenPixelsPerInch')
set(groot,'DefaultRootScreenPixelsPerInch')
The factory value cannot be queried either. This command returns an error as well:
get(groot,'FactoryRootScreenPixelsPerInch')
When using the getframe function (or the print function with the -r0 option) on a
high-DPI system, the size of the image data array that MATLAB returns is larger than in
previous releases. Additionally, the number of elements in the array might not match the
figure size in pixel units. MATLAB reports the figure size based on device-independent
pixels. However, the size of the array is based on the display DPI.
publish Function
When publishing documents on a high-DPI system, the images saved to disk are larger
than in previous releases or on other systems.
9-61
9 Lay Out a Programmatic UI
See Also
Figure | Root
9-62
10
When you develop an app, consider grouping these tasks together in your code file. If an
initialization task involves several steps, consider creating a separate function for that
task.
Examples
Declare Variables for Input and Output Arguments
This example defines the properties in a cell array, mPropertyDefs, and then initializes
the properties.
mPropertyDefs = {...
'iconwidth', @localValidateInput, 'mIconWidth';
'iconheight', @localValidateInput, 'mIconHeight';
'iconfile', @localValidateInput, 'mIconFile'};
mIconWidth = 16; % Use input property 'iconwidth' to initialize
mIconHeight = 16; % Use input property 'iconheight' to initialize
mIconFile = fullfile(matlabroot,'toolbox/matlab/icons/');
% Use input property 'iconfile' to initialize
Each row of the cell array defines one property. It specifies, in order, the name of the
property, the routine that is called to validate the input, and the name of the variable that
holds the property value.
10-2
Initialize a Programmatic App
The following statements start the Icon Editor application. The first statement creates a
new icon. The second statement opens existing icon file for editing.
cdata = iconEditor('iconwidth',16,'iconheight',25)
cdata = iconEditor('iconfile','eraser.gif');
• Identify each property by matching it to the first column of the cell array
• Call the routine named in the second column to validate the input
• Assign the value to the variable named in the third column
When you create the figure window, make it invisible when you create it. Display it only
after you have added all the UI components.
To make the window invisible, set the figure Visible property to 'off' when you create
the figure:
hMainFigure = figure(...
'Units','characters',...
'MenuBar','none',...
'Toolbar','none',...
'Position',[71.8 34.7 106 36.15],...
'Visible','off');
After you have added all the components to the figure window, make the figure visible:
hMainFigure.Visible = 'on';
Most components have a Visible property. Thus, you can also use this property to make
individual components invisible.
If your program allows an output argument, and the user specifies such an argument,
then you want to return the expected output. The code that provides this output usually
appears just before the program’s main function returns.
10-3
10 Code a Programmatic App
1 A call to uiwait blocks execution until uiresume is called or the current figure is
deleted.
2 While execution is blocked, the user creates the icon.
3 When the user clicks OK, that push button’s callback calls the uiresume function.
4 The program returns the completed icon to the user as output.
mIconData contains the icon that the user created or edited. mOutputArgs is a cell
array defined to hold the output arguments. nargout indicates how many output
arguments the user has supplied. varargout contains the optional output arguments
returned by the program. See the complete Icon Editor code file for more information.
See Also
Related Examples
• “Create a Simple App Programmatically” on page 3-2
10-4
Write Callbacks for Apps Created Programmatically
In this section...
“Callbacks for Different User Actions” on page 10-5
“How to Specify Callback Property Values” on page 10-7
This table lists the callback properties that are available, the user actions that trigger the
callback function, and the most common UI and graphics components that use them.
10-5
10 Code a Programmatic App
10-6
Write Callbacks for Apps Created Programmatically
Function handles provide a way to represent a function as a variable. The function must
be a local or nested function in the same file as the app code, or you can write it in a
separate file that is on the MATLAB path.
To create the function handle, specify the @ operator before the name of the function. For
example, this uicontrol command specifies the Callback property to be a handle to
the function pushbutton_callback:
10-7
10 Code a Programmatic App
b = uicontrol('Style','pushbutton','Callback',@pushbutton_callback);
function pushbutton_callback(src,event)
display('Button pressed');
end
Notice that the function handle does not explicitly refer to any input arguments, but the
function declaration includes two input arguments. These two input arguments are
required for all callbacks you specify as a function handle. MATLAB passes these
arguments automatically when the callback executes. The first argument is the UI
component that triggered the callback. The second argument provides event data to the
callback function. If there is no event data available to the callback function, then
MATLAB passes the second input argument as an empty array. The following table lists
the callbacks and components that use event data.
A benefit of specifying callbacks as function handles is that MATLAB checks the function
for syntax errors and missing dependencies when you assign the callback to the
component. If there is a problem in the callback function, then MATLAB returns an error
immediately instead of waiting for the user to trigger the callback. This behavior helps
you to find problems in your code before the user encounters them.
Use a cell array to specify a callback function that accepts additional input arguments
that you want to use in the function. The first element in the cell array is a function
handle. The other elements in the cell array are the additional input arguments you want
to use, separated by commas. The function you specify must define the same two input
10-8
Write Callbacks for Apps Created Programmatically
arguments as described in “Specify a Function Handle” on page 10-7. However, you can
define additional inputs in your function declaration after the first two arguments.
This uicontrol command creates a push button and specifies the Callback property to
be a cell array. In this case, the name of the function is pushbutton_callback, and the
value of the additional input argument is 5.
b = uicontrol('Style','pushbutton','Callback',{@pushbutton_callback,5});
function pushbutton_callback(src,event,x)
display(x);
end
Like callbacks specified as function handles, MATLAB checks callbacks specified as cell
arrays for syntax errors and missing dependencies when you assign the callback to the
component. If there is a problem in the callback function, then MATLAB returns an error
immediately instead of waiting for the user to trigger the callback. This behavior helps
you to find problems in your code before the user encounters them.
Specify an anonymous function when you want a UI component to execute a function that
does not support the two arguments that are required for function handles and cell
arrays. For example, this uicontrol command creates a push button and specifies the
Callback property to be an anonymous function. In this case, the name of function is
myfun, and its function declaration defines only one input argument, x.
b = uicontrol('Style','pushbutton','Callback',@(src,event)myfun(x));
You can specify a character vector when you want to execute a few simple commands, but
the callback can become difficult to manage if it contains more than a few commands. The
character vector you specify must consist of valid MATLAB expressions, which can
include arguments to functions. For example:
hb = uicontrol('Style','pushbutton',...
'String','Plot line',...
'Callback','plot(rand(20,3))');
10-9
10 Code a Programmatic App
'plot(x)'
The variable x must exist in the base workspace when the user triggers the callback, or it
returns an error. The variable does not need to exist at the time you assign callback
property value, but it must exist when the user triggers the callback.
Unlike callbacks that are specified as function handles or cell arrays, MATLAB does not
check character vectors for syntax errors or missing dependencies. If there is a problem
with the MATLAB expression, it remains undetected until the user triggers the callback.
See Also
Related Examples
• “Callbacks for Specific Components” on page 7-12
• “Share Data Among Callbacks” on page 11-2
• “Interrupt Callback Execution” on page 12-2
• “Anonymous Functions”
10-10
11
11-2
Share Data Among Callbacks
hfig = figure;
figname = hfig.Name;
hfig.Name = 'My Window';
If you are using an earlier release, use the get and set functions instead:
hfig = figure;
figname = get(hfig,'Name');
set(hfig,'Name','My Window');
11-3
11 Manage Application-Defined Data
If your code does not have direct access to a component, use the findobj function to
search for that component. If the search is successful, findobj returns the component as
output. Then you can access the component’s properties.
The following app code uses the UserData property to share information about the slider.
To see how it works, copy and paste this code into an editor and run it.
function my_slider()
hfig = figure();
slider = uicontrol('Parent', hfig,'Style','slider',...
'Units','normalized',...
'Position',[0.3 0.5 0.4 0.1],...
'Tag','slider1',...
'UserData',struct('val',0,'diffMax',1),...
'Callback',@slider_callback);
function slider_callback(hObject,eventdata)
sval = hObject.Value;
diffMax = hObject.Max - sval;
data = struct('val',sval,'diffMax',diffMax);
hObject.UserData = data;
% For R2014a and earlier:
% sval = get(hObject,'Value');
% maxval = get(hObject,'Max');
% diffMax = maxval - sval;
% data = struct('val',sval,'diffMax',diffMax);
% set(hObject,'UserData',data);
end
function button_callback(hObject,eventdata)
h = findobj('Tag','slider1');
data = h.UserData;
% For R2014a and earlier:
% data = get(h,'UserData');
display([data.val data.diffMax]);
end
11-4
Share Data Among Callbacks
When the user moves the slider, the slider_callback uses these commands to store
data in a structure:
When the user clicks the push button, the button_callback uses these commands to
retrieve the data:
To set up a GUIDE app for sharing slider data with the UserData property, perform these
steps:
11-5
11 Manage Application-Defined Data
data = struct('val',0,'diffMax',1);
set(handles.slider1,'UserData',data);
11-6
Share Data Among Callbacks
11-7
11 Manage Application-Defined Data
This code uses the handles structure to access the slider. The command, data =
get(handles.slider1,'UserData'), gets the slider’s UserData property. Then,
the display function displays the stored values.
10 Save your code by pressing Save in the Editor Toolstrip.
The first input, obj, is the component object in which to store the data. The second input,
name, is a friendly name that describes the value. The third input, value, is the value you
want to store.
The component, obj, must be the component object containing the data. The second
input, name, must match the name you used to store the data. Unlike the UserData
property, which only holds only one variable, you can use setappdata to store multiple
variables.
This app uses application data to share two values. To see how it works, copy and paste
this code into an editor and run it.
function my_slider()
hfig = figure();
setappdata(hfig,'slidervalue',0);
setappdata(hfig,'difference',1);
11-8
Share Data Among Callbacks
'String','Display Values',...
'Callback',@button_callback);
end
function slider_callback(hObject,eventdata)
diffMax = hObject.Max - hObject.Value;
setappdata(hObject.Parent,'slidervalue',hObject.Value);
setappdata(hObject.Parent,'difference',diffMax);
% For R2014a and earlier:
% maxval = get(hObject,'Max');
% currval = get(hObject,'Value');
% diffMax = maxval - currval;
% parentfig = get(hObject,'Parent');
% setappdata(parentfig,'slidervalue',currval);
% setappdata(parentfig,'difference',diffMax);
end
function button_callback(hObject,eventdata)
currentval = getappdata(hObject.Parent,'slidervalue');
diffval = getappdata(hObject.Parent,'difference');
% For R2014a and earlier:
% parentfig = get(hObject,'Parent');
% currentval = getappdata(parentfig,'slidervalue');
% diffval = getappdata(parentfig,'difference');
display([currentval diffval]);
end
When the user moves the slider, the slider_callback function calculates diffMax.
Then, it uses these commands to modify the application data:
When the user clicks the push button, the button_callback function retrieves the data
using these commands:
11-9
11 Manage Application-Defined Data
To set up a GUIDE app for sharing application data, perform these steps:
setappdata(handles.figure1,'slidervalue',0);
setappdata(handles.figure1,'difference',1);
function myslider_OpeningFcn(hObject,eventdata,handles,varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to junk (see VARARGIN)
11-10
Share Data Among Callbacks
setappdata(handles.figure1,'difference',1);
maxval = get(hObject,'Max');
currval = get(hObject,'Value');
diffMax = maxval - currval;
% Store application data
setappdata(handles.figure1,'slidervalue',currval);
setappdata(handles.figure1,'difference',diffMax);
This callback function has access to the handles structure, so the setappdata
commands store the data in handles.figure1.
9 Add code to the push button callback for retrieving the data. Add these commands to
the end of the function, pushbutton1_Callback.
11-11
11 Manage Application-Defined Data
This callback function has access to the handles structure, so the getappdata
commands retrieve the data from handles.figure1.
10 Save your code by pressing Save in the Editor Toolstrip.
function my_slider()
hfig = figure();
data = struct('val',0,'diffMax',1);
slider = uicontrol('Parent', hfig,'Style','slider',...
'Units','normalized',...
'Position',[0.3 0.5 0.4 0.1],...
'Tag','slider1',...
'Callback',@slider_callback);
11-12
Share Data Among Callbacks
'Callback',@button_callback);
function slider_callback(hObject,eventdata)
sval = hObject.Value;
diffMax = hObject.Max - sval;
% For R2014a and earlier:
% sval = get(hObject,'Value');
% maxval = get(hObject,'Max');
% diffMax = maxval - sval;
data.val = sval;
data.diffMax = diffMax;
end
function button_callback(hObject,eventdata)
display([data.val data.diffMax]);
end
end
The main function defines a struct array called data. When the user moves the slider,
the slider_callback function updates the val and diffMax fields of the data
structure. When the end user clicks the push button, the button_callback function
displays the values stored in data.
The first input, object_handle, is any UI component (typically hObject). The second
input, data, is the variable to store. Every time you call guidata using two input
arguments, MATLAB overwrites any previously stored data. This means you can only
store one variable at a time. If you want to share multiple values, then store the data as a
struct array or cell array.
To retrieve data, call guidata using one input argument and one output argument:
11-13
11 Manage Application-Defined Data
data = guidata(object_handle);
The component you specify to store the data does not need to be the same component
that you use to retrieve it.
If your data is stored as a struct array or cell array, and you want to update one element
without changing the other elements, then retrieve the data and replace it with the
modified array:
data = guidata(hObject);
data.myvalue = 2;
guidata(hObject,data);
To use guidata in a programmatic app, store the data with some initial values in the
main function. Then you can retrieve and modify the data in any callback function.
The following code is a simple example of a programmatic app that uses guidata to
share a structure containing two fields. To see how it works, copy and paste this code into
an editor and run it.
function my_slider()
hfig = figure();
guidata(hfig,struct('val',0,'diffMax',1));
slider = uicontrol('Parent', hfig,'Style','slider',...
'Units','normalized',...
'Position',[0.3 0.5 0.4 0.1],...
'Tag','slider1',...
'Callback',@slider_callback);
function slider_callback(hObject,eventdata)
data = guidata(hObject);
data.val = hObject.Value;
data.diffMax = hObject.Max - data.val;
% For R2014a and earlier:
% data.val = get(hObject,'Value');
11-14
Share Data Among Callbacks
% maxval = get(hObject,'Max');
% data.diffMax = maxval - data.val;
guidata(hObject,data);
end
function button_callback(hObject,eventdata)
data = guidata(hObject);
display([data.val data.diffMax]);
end
When the user moves the slider, the slider_callback function executes these
commands to retrieve and modify the stored data:
When the user clicks the push button, the button_callback function calls guidata to
retrieve a copy of the stored structure. Then it displays the two values stored in the
structure.
GUIDE uses the guidata function to store a structure called handles, which contains all
the UI components. MATLAB passes the handles array to every callback function. If you
want to use guidata to share additional data, then add fields to the handles structure
in the opening function. The opening function is a function defined near the top of your
code file that has _OpeningFcn in the name.
To modify your data in a callback function, modify the handles structure, and then store
it using the guidata function. This slider callback function shows how to modify and
store the handles structure in a GUIDE callback function.
11-15
11 Manage Application-Defined Data
guidata(hObject,handles);
end
11-16
Share Data Among Callbacks
changeme_dialog('changeme_main', handles.figure)
The handles.figure input argument is the Figure object for the changeme_main
dialog box.
The changeme_dialog function retrieves the handles structure from the Figure
object. Thus, the entire set of components in the changeme_main dialog box is available
to the second dialog box.
11-17
11 Manage Application-Defined Data
11-18
See Also
Passing the Figure object between these functions allows the guide_iconEditor window
to access the handles structure of the other two windows. Likewise, the other two
windows can access the handles structure for the guide_iconEditor window.
See Also
Related Examples
• “Nested Functions”
• “Interrupt Callback Execution” on page 12-2
• “Write Callbacks in GUIDE” on page 7-2
• “Write Callbacks for Apps Created Programmatically” on page 10-5
11-19
12
MATLAB lets you control whether or not a callback function can be interrupted while it is
executing. For instance, you can allow users to stop an animation loop by creating a
callback that interrupts the animation. At other times, you might want to prevent
potential interruptions, when the order of the running callback is important. For instance,
you might prevent interruptions for a WindowButtonMotionFcn callback that shows
different sections of an image.
• The Interruptible property of the object owning the running callback determines if
interruption is allowed. A value of 'on' allows the interruption. A value of 'off' does
not allow the interruption. The default value is 'on'.
• If interruption is not allowed, then the BusyAction property (of the object owning the
interrupting callback) determines if MATLAB enqueues or discards the interrupting
callback. A value of 'queue' allows the interrupting callback to execute after the
running callback finishes execution. A value of 'cancel' discards the interrupting
callback. The default value is 'queue'.
12-2
Interrupt Callback Execution
• If the running callback contains one of these commands, then MATLAB stops the
execution of the running callback and executes the interrupting callback. MATLAB
resumes executing the running callback when the interrupting callback completes.
• If the running callback does not contain one of these commands, then MATLAB
finishes executing the callback without interruption.
For more details about the interruptible property and its effects, see the Interruptible
property description on the Uicontrol page.
Example
This example shows how to control callback interruption using the Interruptible and
BusyAction properties and a wait bar.
1 In MATLAB, set your current folder to one in which you have write access.
2 Execute this MATLAB command:
copyfile(fullfile(docroot,
'techdoc','creating_guis','examples',...
'callback_interrupt.m')),fileattrib('callback_interrupt.m',
'+w');
12-3
12 Manage Callback Execution
Clicking specific pairs of buttons demonstrates the effect of different property value
combinations :
12-4
Interrupt Callback Execution
The Interruptible and BusyAction properties are passed as input arguments to the
uicontrol function when each button is created.
Here is the command that creates the Wait (interruptible) push button. Notice that the
Interruptible property is set to 'on'.
h_interrupt = uicontrol(h_panel1,'Style','pushbutton',...
'Position',[30,110,120,30],...
'String','Wait (interruptible)',...
'Tooltip','Interruptible = on',...
'Interruptible','on',...
'Callback',@wait_interruptible);
Here is the command that creates the Wait (uninterruptible) push button. Notice that
the Interruptible property is set to 'off'.
h_nointerrupt = uicontrol(h_panel1,'Style','pushbutton',...
'Position',[30,40,120,30],...
'String','Wait (uninterruptible)',...
'Tooltip','Interruptible = off',...
'Interruptible','off',...
'Callback',@wait_uninterruptible);
Here is the command that creates the Surf Plot (queue) push button. Notice that the
BusyAction property is set to 'queue'.
hsurf_queue = uicontrol(h_panel2,'Style','pushbutton',...
'Position',[30,200,110,30],...
'String','Surf Plot (queue)',...
'BusyAction','queue',...
'Tooltip','BusyAction = queue',...
'Callback',@surf_queue);
12-5
12 Manage Callback Execution
Here is the command that creates the Mesh Plot (cancel) push button. Notice that the
BusyAction property is set to 'cancel'.
hmesh_cancel = uicontrol(h_panel2,'Style','pushbutton',...
'Position',[30,130,110,30],...
'String','Mesh Plot (cancel)',...
'BusyAction','cancel',...
'Tooltip','BusyAction = cancel',...
'Callback',@mesh_cancel);
See Also
drawnow | timer | uiwait | waitfor
Related Examples
• “Write Callbacks for Apps Created Programmatically” on page 10-5
• “Automatically Refresh Plot in a GUIDE App” on page 8-24
• “Schedule Command Execution Using Timer”
• “Finding Code Bottlenecks”
12-6
13
The uitable function creates an empty table. You can populate the table by setting the
Data property. For example, you can create a table containing magic square values.
t =
Table with properties:
13-2
Programmatic App that Displays a Table
Display mixed data types by setting the Data property to a cell array.
t.Data = PatientData;
You can customize the display of a table in several ways. Use the ColumnName property to
add column headings. To create multiline headings, use the pipe (|) symbol.
13-3
13 Examples of Programmatic Apps
To adjust the widths of the columns, specify the ColumnWidth property. The
ColumnWidth property is a 1-by-N cell array, where N is the number of columns in the
table. Set a specific column width, or let MATLAB® set the width based on the contents.
To remove the row names, set the RowName property to an empty array ([]).
t.RowName = [];
13-4
Programmatic App that Displays a Table
Resize the table and remove any extra space using the Position property.
By default, tables use row striping. To turn off row striping, set the RowStriping
property to 'off'. To control the colors of the stripes, set two different colors for the
BackgroundColor property. Use the ForegroundColor property to control the color of
the text.
13-5
13 Examples of Programmatic Apps
To restrict the user's ability to edit data in the table, set the ColumnEditable property.
By default, data cannot be edited in the app. Setting the ColumnEditable property to
true for a column allows the user to edit data in that column.
t.ColumnEditable = [false true true true true];
The ColumnFormat property controls how data is displayed and edited. To specify
choices in a drop-down list, specify a cell array of of character vectors as the column
format. In this example, the Self Assessed Health Status column has a drop-down list
containing four options: Excellent, Fair, Good, and Poor.
13-6
Programmatic App that Displays a Table
Create a Callback
The Table object has two commonly used callbacks. The CellSelectionCallback
executes when the user selects a different cell. The CellEditCallback executes when
the user changes a value in a cell.
t.CellEditCallback = @ageCheckCB;
For example, if you want the Age column to contain values between 0 and 120, set the
CellEditCallback to a function such as this one:
end
If the user enters a value that is outside the acceptable range, the callback function
returns a warning and sets the cell value back to the previous value.
13-7
13 Examples of Programmatic Apps
To see all the properties of the table, use the get command.
get(t)
13-8
Programmatic App that Displays a Table
UserData: []
Visible: 'on'
13-9
App Designer
11
14
• “Create and Run a Simple App Using App Designer” on page 14-2
• “App Designer Versus GUIDE” on page 14-6
• “Displaying Graphics in App Designer” on page 14-9
• “App Designer Preferences” on page 14-14
14 App Designer Basics
14-2
Create and Run a Simple App Using App Designer
1 Drag an Axes component from the Component Library onto the canvas.
2 Drag a Slider component from the Component Library onto the canvas. Place it
below the axes, as in the preceding image.
3 Replace the slider label text. Double-click the label and replace the word Slider
with Amplitude.
4 Above the canvas, click Code View to edit the code. (Notice that you can switch back
to edit your layout by clicking Design View.)
5 In the code view, add a callback function that executes MATLAB commands whenever
the user moves the slider. Right-click app.AmplitudeSlider in the Component
Browser. Then select Callbacks > Add ValueChangedFcn callback in the context
menu. App Designer creates a callback function and places the cursor in the body of
that function.
14-3
14 App Designer Basics
6 Plot the peaks function in the axes. Add this command to the second line of the
AmplitudeSliderValueChanged callback:
plot(app.UIAxes,value*peaks)
Notice that the plot command specifies the target axes (app.UIAxes) as the first
argument. The target axes is always required when you call the plot command in
App Designer.
7 Change the limits of the y-axis by setting the YLim property of the UIAxes object.
Add this command to the third line of the AmplitudeSliderValueChanged
callback:
Notice that the command uses dot notation to access the YLim property. Always use
the pattern app.Component.Property to access property values.
8
Click Run to save and run the app. After saving your changes, your app is
available for running again in App Designer, or by typing its name (without
the .mlapp extension) at the MATLAB command prompt. When you run the app from
the command prompt, the file must be in the current folder or on the MATLAB path.
14-4
See Also
See Also
Related Examples
• “Managing Code in App Designer Code View” on page 17-2
• “Write Callbacks in App Designer” on page 17-18
• “Displaying Graphics in App Designer” on page 14-9
14-5
14 App Designer Basics
If you have existing apps that you developed in GUIDE, consider migrating them to App
Designer.
For assistance in migrating your apps, use the GUIDE to App Designer Migration Tool for
MATLAB. For more information, see https://www.mathworks.com/app-designer/add-
ons.html.
14-6
App Designer Versus GUIDE
14-7
14 App Designer Basics
See Also
Related Examples
• “Create and Run a Simple App Using App Designer” on page 14-2
• “Displaying Graphics in App Designer” on page 14-9
• “Ways to Build Apps” on page 1-2
14-8
Displaying Graphics in App Designer
In this section...
“Calling Graphics Functions” on page 14-9
“Displaying Plots Using Other Types of Axes” on page 14-10
“Unsupported Functionality” on page 14-11
Displaying graphics in App Designer requires a different workflow than you typically use
at the MATLAB command line. Once you understand this workflow and a few special
cases, you will know how to call the functions you need for displaying almost any type of
plot.
This code shows how to specify the target axes when plotting two lines. The first
argument passed to plot and hold is app.UIAxes, which is the default name for the
App Designer axes.
plot(app.UIAxes,[1 2 3 4],'-r');
hold(app.UIAxes);
plot(app.UIAxes,[10 9 4 7],'--b');
Some functions (such as imshow and triplot) use a name-value pair argument to
specify the target object. For example, this code shows how to call the imshow function in
App Designer.
imshow('peppers.png','Parent',app.UIAxes);
Whether you specify the target object as the first argument or a name-value pair
argument depends on the function. See the documentation for the specific function you
want to use to determine the appropriate arguments.
14-9
14 App Designer Basics
theta = 0:0.01:2*pi;
rho = sin(2*theta).*cos(2*theta);
pax = polaraxes(app.UIFigure);
polarplot(pax,theta,rho)
subplot Follow these steps:
For example:
app.UIFigure.AutoResizeChildren = 'off';
ax1 = subplot(1,2,1,'Parent',app.UIFigure);
ax2 = subplot(1,2,2,'Parent',app.UIFigure);
plot(ax1,[1 2 3 4])
plot(ax2,[10 9 4 7])
14-10
Displaying Graphics in App Designer
For example:
app.UIFigure.AutoResizeChildren = 'off';
ax = axes(app.UIFigure);
pareto(ax,[10 20 40 40])
geobubble Specify the parent container when calling these functions (for
heatmap example, app.UIFigure) .
scatterhistogram
stackedplot For example:
wordcloud
h = heatmap(app.UIFigure,rand(10));
geoplot Create the geographic axes by calling the geoaxes function.
geoscatter Specify the parent container as the first input argument (for
geodensityplot example, app.UIFigure). Then call the plotting function with the
axes as the first argument. For example:
latSeattle = 47 + 37/60;
lonSeattle = -(122 + 20/60);
gx = geoaxes(app.UIFigure);
geoplot(gx,latSeattle,lonSeattle)
Unsupported Functionality
As of R2018b, some graphics functionality is not supported in App Designer. This table
lists the functionality that is relevant to most app building workflows.
14-11
14 App Designer Basics
14-12
See Also
See Also
UI Figure | UIAxes
More About
• Graphics Support in App Designer (R2017b - R2018a)
• Graphics Support in App Designer (R2016a - R2017a)
• “App Designer Versus GUIDE” on page 14-6
• “Polar Plotting App in App Designer” on page 18-12
14-13
14 App Designer Basics
Option Description
Display the Welcome to App Designer When selected, a dialog box displays every
dialog box on startup time you start App Designer. The dialog box
contains links to introductory information
and a brief tutorial.
14-14
See Also
Option Description
Show grid with interval When selected, App Designer overlays a
grid onto the canvas as an alignment aide.
You can change the grid spacing to a
specific number of pixels. The default
spacing is 10.
Snap to grid When selected, the upper left corner of a
component always snaps to the intersection
of two grid lines whenever you resize or
move the component on the canvas.
Show alignment hints When selected, App Designer displays
alignment hints as you resize or move a
component on the canvas.
Show resizing hints When selected, App Designer displays the
size of a component as you resize it on the
canvas.
Enable app coding alerts When selected, App Designer flags coding
problems in the editor as you write code.
Include component labels in Component When selected, labels included with
Browser components (such as edit fields) appear as
separate items in the Component
Browser. When this item is not selected,
those labels do not appear in the
Component Browser.
Number of entries (most recently used file This number specifies how many of the
list) most recently accessed apps appear under
the Recent Files section of the Open menu
in the Designer tab.
See Also
Related Examples
• “Lay Out Apps in App Designer” on page 16-2
14-15
15
• “Common Components” on page 15-3 — Include axes for creating plots, and several
components that respond to interactions, such as buttons, sliders, drop-down lists, and
trees.
• “Containers and Figure Tools” on page 15-6 — Include panels and tabs for grouping
components, as well as menu bars.
• “Instrumentation” on page 15-7 — Include gauges and lamps for visualizing status,
as well as knobs and switches for selecting input parameters.
To add a component to your app, drag it onto the canvas from the Component Library.
Then use the Component Properties pane to modify characteristics of the component,
such as the color, font, or text.
15-2
App Designer Components
Common Components
Component Example More Information
Axes UIAxes
Button Button
15-3
15 Component Choices and Customizations
Label Label
15-4
App Designer Components
Spinner Spinner
Table Table
15-5
15 Component Choices and Customizations
15-6
App Designer Components
Instrumentation
Component Example More Information
Gauge Gauge
15-7
15 Component Choices and Customizations
Knob Knob
Lamp Lamp
Switch Switch
15-8
See Also
See Also
Related Examples
• “Create and Run a Simple App Using App Designer” on page 14-2
• “Add UI Components to App Designer Programmatically” on page 15-24
15-9
15 Component Choices and Customizations
Note For information on creating menus in GUIDE, see “Create Menus for GUIDE Apps”
on page 6-78.
A common way to organize tasks in your app is to arrange them in menus at the top of the
window. Most apps group similar tasks into categories, where the top-level menus display
the title of each category. For example, many apps list the Open, Close, and Print tasks
under the top-level menu called File.
15-10
Create Menus for App Designer Apps
Change the menu text by typing directly on the canvas. Commit your changes and
advance to the next menu item by pressing the Tab key.
Add menu items by clicking one of the + buttons below or to the right of the existing
items. Alternatively, you can press the down and right arrow keys.
15-11
15 Component Choices and Customizations
Reorder the menu items by selecting and dragging them to different locations within the
menu.
15-12
Create Menus for App Designer Apps
A common practice is to share callbacks between menu items and other UI components in
the app. This practice allows your users accomplish tasks in different ways, depending on
how they like to work. For more information, see “Use One Callback for Multiple App
Designer Components” on page 17-35.
15-13
15 Component Choices and Customizations
Mnemonics allow users to navigate through menu items by holding down the Alt key and
pressing the key of the underlined character shown in the menu text. To specify a
mnemonic character, go to the Menu Properties pane and insert an ampersand (&)
before one of the characters in the menu text. To make this behavior work, all menu items
must have accelerators. For more information, see the Text property description.
15-14
Create Menus for App Designer Apps
15-15
15 Component Choices and Customizations
Here is an example of a callback function that toggles the state of an axes grid. It also
changes the state of the menu check mark.
See Also
Menu Properties
More About
• “Use One Callback for Multiple App Designer Components” on page 17-35
• “App Designer Keyboard Shortcuts” on page 19-2
15-16
Table Array Data Types in App Designer Apps
Note Only App Designer apps and figures created with the uifigure function support
table arrays. For information on displaying table data in traditional figures, see
“Programmatic App that Displays a Table” on page 13-2.
Table arrays are useful for storing tabular data as MATLAB variables. For example, you
can call the readtable function to create a table array from a spreadsheet.
Table UI components, by contrast, are user interface components that display tabular
data in apps. Starting in R2018a, the types of data you can display in a Table UI
component include table arrays.
When you display table array data in apps, you can take advantage of the interactive
features for certain data types. And unlike other types of arrays that Table UI
components support, table array data does not display according to the ColumnFormat
property of the Table UI component.
Logical Data
In a Table UI component, logical values display as check boxes. true values are
checked, whereas false values are unchecked. When the ColumnEditable property of
the Table UI component is true, the user can select and clear the check boxes in the
app.
f = uifigure;
tdata = table([true; true; false]);
uit = uitable(f,'Data',tdata);
15-17
15 Component Choices and Customizations
Categorical Data
categorical values can appear as drop-down lists or as text. The categories appear in
drop-down lists when the ColumnEditable property of the Table UI component is
true. Otherwise, the categories display as text without a drop-down list.
f = uifigure;
cnames = categorical({'Blue';'Red'},{'Blue','Red'});
w = [400; 700];
tdata = table(cnames,w,'VariableNames',{'Color','Wavelength'});
uit = uitable(f,'Data',tdata,'ColumnEditable',true);
If the categorical array is not protected, users can add new categories in the running
app by typing in the cell.
Datetime Data
datetime values display according to the Format property of the corresponding table
variable (a datetime array).
f = uifigure;
dates = datetime([2016,01,17; 2017,01,20],'Format','MM/dd/uuuu');
m = [10; 9];
tdata = table(dates,m,'VariableNames',{'Date','Measurement'});
uit = uitable(f,'Data',tdata);
15-18
Table Array Data Types in App Designer Apps
To change the format, use dot notation to set the Format property of the table variable.
Then, replace the data in the Table UI component.
tdata.Date.Format = 'dd/MM/uuuu';
uit.Data = tdata;
When the ColumnEditable property of the Table UI component is true, users can
change date values in the app. When the column is editable, the app expects input values
that conform to the Format property of the datetime array. If the user enters an invalid
date, the value displayed in the table is NaT.
Duration Data
duration values display according to the Format property of the corresponding table
variable (a duration array).
f = uifigure;
mtime = duration([0;0],[1;1],[20;30]);
dist = [10.51; 10.92];
tdata = table(mtime,dist,'VariableNames',{'Time','Distance'});
uit = uitable(f,'Data',tdata);
To change the format, use dot notation to set the Format property of the table variable.
tdata.Time.Format = 's';
uit.Data = tdata;
15-19
15 Component Choices and Customizations
Cells containing duration values are not editable in the running app, even when
ColumnEditable of the Table UI component is true.
Nonscalar Data
Nonscalar values display in the app the same way as they display in the Command
Window. For example, this table array contains 3-D arrays and struct arrays.
f = uifigure;
arr = {rand(3,3,3); rand(3,3,3)};
s = {struct; struct};
tdata = table(arr,s,'VariableNames',{'Array','Structure'});
uit = uitable(f,'Data',tdata);
A multicolumn table array variable displays as a combined column in the app, just as it
does in the Command Window. For example, the RGB variable in this table array is a 3-
by-3 array.
n = [1;2;3];
rgbs = [128 122 16; 0 66 155; 255 0 0];
tdata = table(n,rgbs,'VariableNames',{'ROI','RGB'})
tdata =
3×2 table
ROI RGB
___ _________________
1 128 122 16
15-20
Table Array Data Types in App Designer Apps
2 0 66 155
3 255 0 0
The Table UI component provides a similar presentation. Selecting an item in the RGB
column selects all the subcolumns in that row. The values in the subcolumns are not
editable in the running app, even when ColumnEditable property of the Table UI
component is true.
f = uifigure;
uit = uitable(f,'Data',tdata);
If the ColumnEditable property of the Table UI component is true, then the user can
correct the values in the running app.
f = uifigure;
sz = categorical([1; 3; 4; 2],1:3,{'Large','Medium','Small'});
num = [NaN; 10; 12; 15];
tdata = table(sz,num,'VariableNames',{'Size','Number'});
uit = uitable(f,'Data',tdata,'ColumnEditable',true);
15-21
15 Component Choices and Customizations
The StartupFcn callback loads a spreadsheet into a table array. Then a subset of the
data displays and is plotted in the app. Both plots update when the user edits a value in
the app.
15-22
See Also
See Also
Table (App Designer) | uitable
Related Examples
• “Write Callbacks in App Designer” on page 17-18
• “Create Helper Functions in App Designer” on page 17-24
15-23
15 Component Choices and Customizations
• Creating components that are not available in the Component Library. For example,
an app that displays a dialog box must call the appropriate function to display the
dialog box.
• Creating components dynamically according to run-time conditions.
When you add UI components programmatically, you must call the appropriate function to
create the component, assign a callback to the component, and then write the callback as
a helper function.
When you call a function to create a component, specify the figure or one of its child
containers as the parent object. For example, this command creates a button and
specifies the figure as the parent object. In this case, the figure has the default name that
App Designer assigns (app.UIFigure).
b = uibutton(app.UIFigure);
Next, specify the component's callback property as a function handle of the form
@app.callbackname. For example, this command sets the ButtonPushedFcn property
of button b to a callback function named mybuttonpress.
b.ButtonPushedFcn = @app.mybuttonpress;
15-24
Add UI Components to App Designer Programmatically
function mybuttonpress(app,src,event)
disp('Have a nice day!');
end
end
To write a callback that accepts additional input arguments, specify the additional
arguments after the first three. For example, this callback has accepts two additional
inputs, x and y:
function addxy(app,src,event,x,y)
disp(x + y);
end
end
To assign this callback to a component, specify the component's callback property as cell
array. The first element in the cell array must be the function handle. Subsequent
elements must be the additional input values. For example:
b.ButtonPushedFcn = {@app.addxy,10,20};
When the user clicks the window's close button (X), a dialog box displays to confirm that
the user wants to close the app. When the user dismisses the dialog box, the CloseFcn
callback executes.
15-25
15 Component Choices and Customizations
When the user clicks a patient name in the tree, the Patient Information panel displays
data such as age, gender, and health status. The app stores changes to the data in a table
array.
15-26
See Also
See Also
More About
• “Write Callbacks in App Designer” on page 17-18
• “Create Helper Functions in App Designer” on page 17-24
15-27
16
App Layout
To add a component to your app, drag it from the Component Library onto the canvas.
The name of the component appears in the Component Browser after you add it to the
canvas. You can select components in either the canvas or the Component Browser. The
selection occurs in both places simultaneously.
Some components, such as edit fields and sliders, are grouped with a label when you drag
them onto the canvas. These labels do not appear in the Component Browser by default,
but you can add them to the list by right-clicking anywhere in the Component Browser
and selecting Include component labels in Component Browser. If you do not want
the component to have a label, you can exclude it by pressing and holding the Ctrl key as
you drag the component onto to the canvas.
16-2
Lay Out Apps in App Designer
If a component has a label, and you change the label text, the name of the component in
the Component Browser changes to match that text. You can customize the name of the
component by double-clicking it and typing a new name.
Customizing Components
You can customize the appearance of a component by selecting it and then editing its
properties in the Component Properties pane. For example, you can change the font
size of a button in this pane.
Some properties control the behavior of the component. For example, you can change the
range of values that a numeric edit field accepts by changing the Limits property.
16-3
16 App Layout
When the app runs, the edit field accepts values only within that range.
You can edit some properties directly in the canvas by double-clicking the component. For
example, you can edit a button label by double-clicking it and typing the desired text. To
add multiple lines of text, hold down the Shift key and press Enter.
App Designer provides alignment hints to help you align components as you drag them in
the canvas. Orange dotted lines passing through the centers of multiple components
indicate that their centers are aligned. Orange solid lines at the edges indicate that the
edges are aligned. Perpendicular lines indicate that a component is centered in its parent
container.
16-4
Lay Out Apps in App Designer
As an alternative to dragging components on the canvas, you can align components using
the tools in the Align section of the toolstrip.
When you use an alignment tool, the selected components align to an anchor component.
The anchor component is the last component selected, and it has a thicker selection
border than the other components. To select a different anchor, hold down the Ctrl or
Shift key and click the desired component twice (once to deselect the component, and a
second time to select it again). For example, in the following image, the Format Options
label is the anchor. Clicking the Align left button aligns the left edges of the drop-
down and check box to the left edge of the label.
You can control the spacing among neighboring components using the tools in the Space
section of the toolstrip. Select a group of three or more components, and then select an
option from the drop-down list in the Space section of the toolstrip. The Evenly option
distributes the space evenly within the space occupied by the components. The 20 option
spaces the components 20 pixels apart. If you want to customize the number of pixels
between the components, type a number into the drop-down list.
16-5
16 App Layout
Next, click Apply Horizontally or Apply Vertically . For example, select Evenly
and then click Apply Vertically to distribute the space among a vertical stack of
components.
Grouping Components
You can group two or more components together to modify them as a single unit. For
example, you might group a set of components after finalizing their relative positions, so
that you can move them without changing that relationship.
To group a set of components, select them in the canvas, right-click, and then select
Grouping > Group in the Arrange section of the toolstrip.
The Grouping tool also provides functionality for these common tasks:
16-6
Lay Out Apps in App Designer
• Ungroup all components in a group — Select the group. Then select Grouping >
Ungroup.
• Add a component to a group — Select the component and the group. Then select
Grouping > Add to Group.
• Remove a component from a group — Select the component. Then select Grouping >
Remove from Group.
The Component Browser shows the parent–child relationship by indenting the name of
the child component under the parent container.
16-7
16 App Layout
See Also
More About
• “App Designer Components” on page 15-2
• “App Designer Keyboard Shortcuts” on page 19-2
• “Managing Resizable Apps in App Designer” on page 16-9
16-8
Managing Resizable Apps in App Designer
You can disable the automatic resize behavior by disabling the property. To disable the
property in App Designer, select the container and clear the AutoResizeChildren
check box in the Component Properties pane.
Whenever you select or clear this check box, App Designer sets the property to the same
value on all its child containers. To set the AutoResizeChildren property of a child
container to a different value, set the value for the child container after setting the value
for the parent.
16-9
16 App Layout
You can also set the property programmatically by setting the value to 'on' or 'off'.
When you set the property programmatically, the value does not change for the child
containers.
app.UIFigure.AutoResizeChildren = 'off';
If the automatic resize behavior is not the behavior that you want, disable the
AutoResizeChildren property and write a SizeChangedFcn callback for the
container. In this callback, you write code to adjust the Position property of the child
components. The callback executes when the size of the container changes.
For example, a SizeChangedFcn might contain code that keeps the width of an edit field
at one quarter of the width of the figure.
figwidth = app.UIFigure.Position(3);
app.EditField.Position(3) = .25 * figwidth;
Note Starting in R2017a, you must disable the AutoResizeChildren property to allow
the SizeChangedFcn callback to execute. For more information, see “App Designer:
Disable automatic resize behavior when writing SizeChangedFcn callbacks”.
To completely disable resizing, set the Resize property of the figure to 'off'.
See Also
UI Figure
16-10
See Also
More About
• “Lay Out Apps in App Designer” on page 16-2
• “Write Callbacks in App Designer” on page 17-18
16-11
16 App Layout
Note Grid layout managers are only for apps created using the uifigure function.
When you design an app using a grid layout manager, you place components in the rows
and columns of an invisible grid. Using a grid layout is straightforward, but it is important
to understand the relationship between the grid, its parent container, and the components
that the grid manages.
When you create a grid, it always spans the entire app window or container that you
place it in. You must configure its rows and columns so that they divide the space of the
parent container appropriately.
To configure the rows and columns, specify the RowHeight and ColumnWidth properties
of the grid. Specify the value of each property as a cell array. The length of the cell array
controls the number of rows or columns. For example, to create a grid that has three
rows, specify the RowHeight property as a 1-by-3 cell array. The values in each cell array
control the size of each row or column.
• Fixed size in pixels — Specify a number. The size of the row or column is fixed at the
number of pixels you specify. When the parent container resizes, the size does not
change.
• Variable size — Specify a number paired with an 'x' character (for example, '1x').
When the parent container resizes, the row or column grows or shrinks. Variable-size
rows and columns fill the remaining space that the fixed rows or columns do not use.
The number you pair with the 'x' character is a weight for dividing up the remaining
space among all the variable-size rows or columns.
For example, this code creates a 2-by-3 grid. The first row is fixed at 25 pixels high, while
the second row has a variable height. The first two columns are 100 pixels wide, and the
last column has a variable width.
f = uifigure;
g = uigridlayout(f);
g.RowHeight = {25,'1x'};
g.ColumnWidth = {100,100,'1x'};
16-12
Using Grid Layout Managers
The grid is invisible, but this picture includes lines to illustrate how the space is
distributed.
To place a component in a specific row and column of the grid, you must:
For example, this code creates a grid that has the default size (two '1x' rows and two
'1x' columns). Then it places a list box in the first row and second column of that grid.
g = uigridlayout;
list = uilistbox(g);
list.Layout.Row = 1;
list.Layout.Column = 2;
Again, the grid lines in this picture do not appear in the figure.
16-13
16 App Layout
If you add components and do not specify the Layout property, the grid places the
components in default locations. The components fill the grid from left to right and top to
bottom initially. For example, this code creates a 2-by-2 grid containing four components
in the default order.
f = uifigure;
g = uigridlayout(f);
g.RowHeight = {25,'1x'};
g.ColumnWidth = {100,'1x'};
b = uibutton(g,'Text','Open File');
dd = uidropdown(g,'Items',{'Scatter Plot','Line Plot'});
list = uilistbox(g,'Items',{'one','two'});
ax = uiaxes(g);
16-14
Using Grid Layout Managers
If you reconfigure the grid after adding components to it, the grid does not redistribute
the components. For example, if you add a third column in the preceding example, the
grid does not shift the list box back to the third column of the first row.
g.ColumnWidth = {100,'1x','1x'};
16-15
16 App Layout
Some changes you make in the layout can change the size of the grid. For example,
adding a component to a fully populated grid adds a row to accommodate the new
component.
To view the list of component objects in the grid, query the Children property of the
grid. Changing the order in the list does not change the layout in the grid.
• Creates grid1, a 1-by-2 grid in the figure that manages a panel and an axes
component.
• Creates grid2, a 3-by-2 grid inside the panel. This grid manages the layout of a drop-
down menu, two spinners, and their labels.
16-16
Using Grid Layout Managers
Create a program file called showhide.m. Then paste this code into the file and run it.
function showhide
f = uifigure('Name','Statistical Analysis');
function findMethodSelected(src,~)
method = src.Value;
switch method
case 'Quartiles'
% Collapse the second row (hides winSize spinner)
grid2.RowHeight{2} = 0;
16-17
16 App Layout
When you set the Find Method to Quartiles in the app, the Window Size label and the
spinner next to it become hidden.
See Also
GridLayout Properties | uigridlayout
16-18
17
App Programming
17-2
Managing Code in App Designer Code View
• The body of functions you define (e.g., callbacks and helper functions)
• Custom property definitions
17-3
17 App Programming
Managing UI Components
When you add a UI component to your app, App Designer assigns a default name to the
component. Use that name (including the app prefix) to refer to the component in your
code. You can change the name of a component by double-clicking the name in the
Component Browser and typing a new name. App Designer automatically updates all
references to that component when you change its name.
17-4
Managing Code in App Designer Code View
To use the name of a component in your code, you can save some time by copying the
name from the Component Browser. Right-click the component name and select Insert
at Cursor. Alternatively, you can drag the component name from the list into your code.
To delete a component, select its name in the Component Browser and press the Delete
key.
Managing Callbacks
If you delete a component from your app, App Designer deletes the associated callback
only if the callback has not been edited and is not shared with other components.
To delete a callback manually, select the callback name in the Callbacks tab of the Code
Browser and press the Delete key.
For more information about callbacks, see “Write Callbacks in App Designer” on page 17-
18.
17-5
17 App Programming
To store data, and share it among different callbacks, create a custom property. For
example, you might want your app to read a data file and allow different callbacks in your
app to access that data.
To create a property, expand the Property drop-down in the Editor tab, and select
Private Property or Public Property. App Designer creates a template property
definition and places your cursor next to that definition. Change the name of the property
as desired.
properties (Access = public)
X % Average cost
end
To reference the property in your code, use dot notation of the form app.Propertyname.
For example, app.X references the property named X.
For more information about creating and using custom properties, see “Share Data Within
App Designer Apps” on page 17-28.
If you want to execute a block of code in multiple parts of your app, create a helper
function. For example, you might want to update a plot after the user changes a number
in an edit field or selects an item in a drop-down list. Creating a helper function allows
you to single-source the common commands and avoid having to maintain redundant sets
of code.
To add a helper function, expand the Function drop-down in the Editor tab, and
select Private Function or Public Function. App Designer creates a template function
and places your cursor in the body of that function.
To delete a helper function, select the function name in the Functions tab of the Code
Browser and press the Delete key.
For more information about writing helper functions, see “Create Helper Functions in App
Designer” on page 17-24.
To add input arguments to your app, click App Input Arguments in the Editor tab.
Input arguments are commonly used for creating apps that have multiple windows. For
17-6
See Also
more information, see “Startup Tasks and Input Arguments in App Designer” on page 17-
8.
If you run your app directly from App Designer (by clicking Run ), App Designer
highlights the source of errors in your code, should any errors occur at run time. To hide
the error message, click the error indicator (the red circle). To make the error indicator
disappear, fix your code and save your changes.
See Also
Related Examples
• “Write Callbacks in App Designer” on page 17-18
• “Share Data Within App Designer Apps” on page 17-28
• “Create Helper Functions in App Designer” on page 17-24
• “Startup Tasks and Input Arguments in App Designer” on page 17-8
17-7
17 App Programming
App designer creates the function and places the cursor in the body of the function. Add
commands to this function as you would do for any callback function. Then save and run
your app.
17-8
Startup Tasks and Input Arguments in App Designer
See “Data Analysis App in App Designer” on page 18-4 for an example of an app that
has a StartupFcn callback.
To add input arguments to an app, open the app in App Designer and click Code View.
Then click App Input Arguments in the Editor tab.
The App Input Arguments dialog box allows you to add or remove input arguments in
the function signature of the StartupFcn callback. The app argument is always first, so
you cannot change that part of the signature. Enter a comma-separated list of variable
names for your input arguments. You can also enter varargin to make any of the
arguments optional. Then click OK.
17-9
17 App Programming
After you click OK, App Designer creates a StartupFcn callback that has the function
signature you defined in the dialog box. If your app already has a StartupFcn callback,
then the function signature is updated to include the new input arguments.
After you have created the input arguments and coded the StartupFcn, you can test the
app. Expand the drop-down list from the Run button in the toolstrip. In the second menu
item, specify comma-separated values for each input argument. The app runs after you
enter the values and press Enter.
Note MATLAB might return an error if you click the Run button without entering input
arguments in the drop-down list. The error occurs because the app has required input
arguments that you did not specify.
After successfully running the app with a set of input arguments, the Run button icon
contains a blue circle.
The blue circle indicates that your last set of input values are available for re-running
your app without having to type them again. Up to seven sets of input values are available
to choose from. Click the top half of the Run button to re-run the app with the last set of
values. Or, click the bottom half of the Run button and select one of the previous sets of
values.
17-10
See Also
The Run button also allows you to change the list of arguments in the function signature.
Select Edit App Input Arguments... from the drop-down list in the bottom half of the
Run button.
Alternatively, you can open the same App Input Arguments dialog box by clicking App
Input Arguments in the toolstrip, or by right-clicking the StartupFcn callback in
the Code Browser.
See “Creating Multiwindow Apps in App Designer” on page 17-12 for an example of an
app that uses input arguments.
See Also
Related Examples
• “Write Callbacks in App Designer” on page 17-18
• “Creating Multiwindow Apps in App Designer” on page 17-12
17-11
17 App Programming
• When the dialog box opens, the main app passes information to the dialog box by
calling the dialog box app with input arguments.
• When the user clicks the OK button in the dialog box, the dialog box returns
information to the main app by calling a public function in the main app with input
arguments.
• “Send Information to the Dialog Box” on page 17-13 — Write a StartupFcn callback
in the dialog box app that accepts input arguments. One of the input arguments must
be the main app object. Then, in the main app, call the dialog box app with the input
arguments.
17-12
Creating Multiwindow Apps in App Designer
• “Return Information to the Main App” on page 17-14 — Write a public function in the
main app that updates the UI based on the user's selections in the dialog box. Because
it is a public function, the dialog box can call it and pass values to it.
• “Manage Windows When They Close” on page 17-15 — Write CloseRequest
callbacks in both apps that perform maintenance tasks when the windows close.
To see an implementation of all the steps in this process, see Plotting App That Opens a
Dialog Box on page 17-16.
1 In the dialog box app, define input arguments for the StartupFcn callback, and then
add code to the callback. Open the dialog box app into Code View. In the Editor tab,
click App Input Arguments . In the App Input Arguments dialog box, enter a
comma-separated list of variable names for your input arguments. Designate one of
the inputs as a variable that stores the main app object. Then click OK.
function StartupFcn(app,mainapp,sz,c)
% Store main app object
app.CallingApp = mainapp;
17-13
17 App Programming
For a fully coded example of a StartupFcn callback, see Plotting App That Opens a
Dialog Box on page 17-16.
2 Call the dialog box app from within a callback in the main app. Open the main app
into Code View and add a callback function for the Options button. This callback
disables the Options button to prevent users from opening multiple dialog boxes.
Next, it gets the values to pass to the dialog box, and then it calls the dialog box app
with input arguments and an output argument. The output argument is the dialog box
app object.
function OptionsButtonPushed(app,event)
% Disable Plot Options button while dialog is open
app.OptionsButton.Enable = 'off';
Change the default function name to the desired name, and add input arguments for
each option you want to pass from the dialog box to the main app. The app argument
must be first, so specify the additional arguments after that argument. Then add code
to the function that processes the inputs and updates the main app.
function updateplot(app,sz,c)
% Process sz and c
17-14
Creating Multiwindow Apps in App Designer
...
end
For a fully coded example of a public function, see Plotting App That Opens a Dialog
Box on page 17-16.
2 Create a property in the dialog box app to store the main app. Open the dialog box
app into Code View, and create a private property called CallingApp. Select
Property > Private Property in the Editor tab. Then change the property name in
the properties block to CallingApp.
In this callback, pass the CallingApp property and the user's selections to the
public function. Then call the delete function to close the dialog box.
function ButtonPushed(app,event)
% Call main app's public function
updateplot(app.CallingApp,app.EditField.Value,app.DropDown.Value);
1 Open the dialog box app into Code View, right-click the app.UIFigure object in the
Component Browser, and select Callbacks > Add CloseRequestFcn callback.
Then add code that re-enables the button in the main app and closes the dialog box
app.
function DialogAppCloseRequest(app,event)
% Enable the Plot Options button in main app
app.CallingApp.OptionsButton.Enable = 'on';
17-15
17 App Programming
function MainAppCloseRequest(app,event)
% Delete both apps
delete(app.DialogApp)
delete(app)
end
17-16
See Also
See Also
More About
• “Write Callbacks in App Designer” on page 17-18
• “Startup Tasks and Input Arguments in App Designer” on page 17-8
17-17
17 App Programming
Note For information on callbacks in GUIDE, see “Write Callbacks in GUIDE” on page 7-
2. If you are creating an app programmatically, see “Write Callbacks for Apps Created
Programmatically” on page 10-5.
A callback is a function that executes when a user interacts with a UI component in your
app. Most components can have at least one callback. However some components, such
as labels and lamps, do not have callbacks because those components only display
information.
To see the list of callbacks that a component supports, select the component and click the
Callbacks tab in the component Properties pane.
17-18
Write Callbacks in App Designer
• Select the Callbacks tab in the component Properties pane. The left side of the
Callbacks tab shows a list of supported callback properties. The text field next to each
callback property allows you to specify a name for the callback function. The down-
arrow next to the text field allows you to select a default name in angle brackets <>. If
your app has existing callbacks, the drop-down includes those callbacks. Select an
existing callback when you want multiple UI components to execute the same code.
17-19
17 App Programming
•
In code Code View, in the Editor tab, click Callbacks . Or in the Code Browser
on the Callbacks tab, click the button.
Specify the following options in the Add Callback Function dialog box:
• app — The app object. Use this object to access UI components in the app as well as
other variables stored as properties.
17-20
Write Callbacks in App Designer
• event — An object that contains specific information about the user's interaction with
the UI component.
The app argument provides the app object to your callback. You can access any
component (and all component-specific properties) within any callback by using this
syntax:
app.Component.Property
For example, this command sets the Value property of a gauge to 50. In this case, the
name of the gauge is PressureGauge.
app.PressureGauge.Value = 50;
The event argument provides an object that has different properties, depending on the
specific callback that is executing. The object properties contain information that is
relevant to the type of interaction that the callback is responding to. For example, the
event argument in a ValueChangingFcn callback of a slider contains a property called
Value. That property stores the slider value as the user moves the thumb (before they
release the mouse). Here is a slider callback function that uses the event argument to
make a gauge track the value of the slider.
To learn more about the event argument for a specific component's callback function,
see the property page for that component. Right-click the component, and select Help on
Selection to open the property page. For a list of property pages for all UI components,
see “Designing Apps in App Designer”.
17-21
17 App Programming
Click a search result to scroll the callback into view. Right-clicking a search result and
selecting Go To places your cursor in the callback function.
Deleting Callbacks
Delete a callback by right-clicking the callback in the Callbacks tab of the Code
Browser and selecting Delete from the context menu.
17-22
See Also
See Also
Related Examples
• “Share Data Within App Designer Apps” on page 17-28
• “Use One Callback for Multiple App Designer Components” on page 17-35
17-23
17 App Programming
There are two types of helper functions: private functions, which you can call only inside
your app, and public functions, which you can call either inside or outside your app.
Private functions are commonly used in single-window apps, while public functions are
commonly used in multiwindow apps.
• Expand the drop-down menu from the bottom half of the Function button in the
Editor tab. Select Private Function or Public Function.
• Select the Functions tab in the Code Browser, expand the drop-down list on the
button, and select Private Function or Public Function.
17-24
Create Helper Functions in App Designer
When you make your selection, App Designer creates a template function and places your
cursor in the body of that function. Then you can update the function name and its
arguments, and add your code to the function body. The app argument is required, but
you can add more arguments after the app argument. For example, this function creates
a surface plot of the peaks function. It accepts an additional argument n for specifying
the number of samples to display in the plot.
function updateplot(app,n)
surf(app.UIAxes,peaks(n));
colormap(app.UIAxes,winter);
end
end
Call the function from within any callback. For example, this code calls the updateplot
function and specifies 50 as the value for n.
updateplot(app,50);
If your app has numerous helper functions, you can quickly search and navigate to a
specific function by typing part of the name in the search bar at the top of the Functions
17-25
17 App Programming
tab. After you begin typing, the Functions tab clears, except for the items that match
your search.
Click a search result to scroll the function into view. Right-clicking a search result and
selecting Go To places your cursor in the function.
To delete a helper function, select its name in the Functions tab and press the Delete
key.
17-26
See Also
See Also
Related Examples
• “Write Callbacks in App Designer” on page 17-18
• “Creating Multiwindow Apps in App Designer” on page 17-12
17-27
17 App Programming
Note For information on sharing data in apps you create using GUIDE, see “Share Data
Among Callbacks” on page 11-2.
Using properties is the best way to share data within an app because properties are
accessible to all functions and callbacks in an app. All UI components are properties, so
you can use this syntax to access and update UI components within your callbacks:
app.Component.Property
For example, these commands get and set the Value property of a gauge. In this case,
the name of the gauge is PressureGauge.
However, if you want to share an intermediate result, or data that multiple callbacks need
to access, then define a public or private property to store your data. Public properties
are accessible both inside and outside of the app, whereas private properties are only
accessible inside of the app. Code View provides a few different ways to create a
property:
• Expand the drop-down menu from the bottom half of the Properties button in the
Editor tab. Select Private Property or Public Property.
17-28
Share Data Within App Designer Apps
• Click on the Properties tab in the Code Browser, expand the drop-down list on the
button, and select Private Property or Public Property.
After you select an option to create a property, App Designer adds a property definition
and a comment to a properties block.
The properties block is editable, so you can change the name of the property and edit
the comment to describe the property. For example, this property stores a value for
average cost:
If your code needs to access a property value when the app starts, you can initialize its
value in the properties block or in the StartupFcn callback.
Elsewhere in your code, use dot notation to get or set the value of a property:
17-29
17 App Programming
See Also
Related Examples
• “Write Callbacks in App Designer” on page 17-18
17-30
See Also
17-31
17 App Programming
If you open an app for editing that was created in a previous release, App Designer
updates the app, and displays a message such as this one.
After saving your changes, the new format is not recognized if you try to edit the app in a
previous release of App Designer. You might see a message such as this.
To enable editing of newer apps in a previous release (R2017b, R2017a, or R2016b), save
the app in the release-specific format. Select Save > Save Copy As from any of the tabs
in the toolstrip.
17-32
Compatibility Between Different Releases of App Designer
In the Save Copy As window, select a type from the Save as Type drop-down list.
17-33
17 App Programming
• To save your app in a format that can be edited in earlier releases, use Save Copy As.
When you use this option, App Designer saves the copy of the app in the specified
folder, but it does not replace the app in your current session.
• To save a copy of your app that is editable only with the current release, use Save As.
When you use this option, App Designer saves the copy of the app in the specified
folder and replaces the app in your current session.
See Also
appdesigner
17-34
Use One Callback for Multiple App Designer Components
1 In App Designer, drag an Axes component from the Component Library onto the
canvas. Then make these changes:
17-35
17 App Programming
• Double-click the label next to the edit field and change it to Levels:.
• Double-click the edit field and change the default value to 20.
3 Drag a Button component next to the edit field on the canvas. Then double-click its
label and change it to Update Plot.
4 Add a callback function that executes when the user clicks the button. Right-click the
Update Plot button and select Callbacks > Add ButtonPushedFcn callback.
5 App Designer switches to the Code View. Paste this code into the body of the
UpdatePlotButtonPushed callback:
Z = peaks(100);
nlevels = app.LevelsEditField.Value;
contour(app.UIAxes,Z,nlevels);
6 Next, share the callback with the edit field. In the Component Browser, right-click
the app.LevelsEditField component and select Callbacks > Select existing
callback.... When the Select Callback Function dialog box displays, select
UpdatePlotButtonPushed from the Name drop-down menu.
Sharing this callback allows the user to update the plot after changing the value in
the edit field and pressing Enter. Alternatively, they can change the value and press
the Update Plot button.
17-36
Use One Callback for Multiple App Designer Components
7 Next, set the axes aspect ratio and limits. In the Component Browser, select the
app.UIAxes component. Then make the following changes in the UIAxes
Properties panel:
17-37
17 App Programming
To disconnect a callback that is shared with a component, select the component in the
Component Browser. Then click the Callbacks tab in the properties panel and select
<no callback> from the drop-down menu. Selecting this option only disconnects the
callback from the component. It does not delete the function definition from your code,
nor does it disconnect the callback from any other components.
After you disconnect a callback, you can create a new callback for the component or leave
the component without a callback function.
See Also
Related Examples
• “Write Callbacks in App Designer” on page 17-18
17-38
18
• Numeric edit fields — allow users to enter values for the loan amount, interest rate,
and loan period. MATLAB® automatically checks to make sure the values are numeric
and within the range specified by the app. A fourth numeric edit field displays the
resulting monthly payment amount based on the inputs.
• Push button — executes a callback function to calculate the monthly payment value.
• Axes — used to plot the principal and interest amounts versus mortgage installment.
See Also
UIAxes
18-2
See Also
Related Examples
• “Write Callbacks in App Designer” on page 17-18
18-3
18 App Designer Examples
• Check boxes — used to update the plot with male or female data when the user
toggles a check box.
• Switch — used to switch between visualizing systolic and diastolic data.
• Button group containing radio buttons — used to manage exclusive selection of radio
buttons. When the user selects a radio button, the button group executes a callback
function to update the plot with the appropriate data.
• Slider — used to adjust histogram bin width. This slider only appears when the
Histogram plotting option is selected in the button group.
• Table — used to view the data associated with the chart.
18-4
See Also
See Also
Table | UIAxes
Related Examples
• “Write Callbacks in App Designer” on page 17-18
18-5
18 App Designer Examples
• Numeric edit fields — allow users to enter the pulse frequency and length. MATLAB®
automatically checks to make sure the values are numeric and within the range
specified by the app.
• Switches — allow users to control automatic plot updates and toggle between plots in
the time and frequency domains.
• Drop-down menu — allows users to select from a list of pulse shapes, such as
Gaussian, sinc, and square.
• Knobs — allow users to modify the pulse by specifying a window function, modulating
the signal, or applying other enhancements.
See Also
UIAxes
18-6
See Also
Related Examples
• “Write Callbacks in App Designer” on page 17-18
18-7
18 App Designer Examples
In addition to the tree and Patient Information panel, the app also contains the
following UI components:
18-8
See Also
See Also
readtable | table | uitree | uitreenode
Related Examples
• “Add UI Components to App Designer Programmatically” on page 15-24
18-9
18 App Designer Examples
18-10
See Also
See Also
UIAxes | imagesc | imread | uialert
18-11
18 App Designer Examples
• Creating different types of axes programmatically to display plots that uiaxes does
not support
• Calling a plotting function in App Designer
• Sharing a callback with multiple components
• Displaying Unicode® characters in a label
18-12
See Also
See Also
polaraxes | polarplot
Related Examples
• “Displaying Graphics in App Designer” on page 14-9
18-13
18 App Designer Examples
See Also
readtable | table
18-14
See Also
Related Examples
• “Table Array Data Types in App Designer Apps” on page 15-17
18-15
18 App Designer Examples
• Writing a callback for an object created programmatically (in this case, the timer
object)
• Configuring a timer object to execute its callback at regular intervals
• Starting the timer when the user clicks the Start button
• Stopping the timer when the user clicks the Stop button
• Deleting the timer when the app closes
18-16
See Also
See Also
UIAxes | memory | timer
18-17
18 App Designer Examples
• Writing a callback for an object created programmatically (in this case, the timer
object)
• Configuring a timer object to execute its callback at regular intervals
• Starting the timer when the user clicks the Start button
• Stopping the timer when the user clicks the Stop button
• Deleting the timer when the app closes
18-18
See Also
See Also
UIAxes | timer | webread
18-19
18 App Designer Examples
18-20
See Also
See Also
Related Examples
• “Creating Multiwindow Apps in App Designer” on page 17-12
• “Startup Tasks and Input Arguments in App Designer” on page 17-8
• “Create Helper Functions in App Designer” on page 17-24
18-21
19
Keyboard Shortcuts
19 Keyboard Shortcuts
19-2
App Designer Keyboard Shortcuts
19-3
19 Keyboard Shortcuts
Action Shortcut
Add component and associated label (if any) Click the component and hold down the
to canvas. mouse key to drag the component from the
Component Library on the left into the
design area.
Add component only to canvas. Hold down the Ctrl key, click the
component, and drag it from the
Component Library on the left into the
design area.
Select the components that you want to group, and then press Ctrl + G. All components
to be grouped must have the same parent component.
19-4
App Designer Keyboard Shortcuts
This table summarizes the keyboard shortcuts for moving selected components and
groups.
Action Key
Resize component while maintaining aspect Press and hold down the Shift key before
ratio. you begin to drag the component resize
handle.
Resize component while keeping center Press and hold down the Ctrl key before
location unchanged. you begin to drag the component resize
handle.
Resize component while maintaining aspect Press and hold down the Ctrl and Shift
ratio and keeping center location keys before you begin to drag the
unchanged. component resize handle.
Cancel an in-progress resize operation. Escape
19-5
19 Keyboard Shortcuts
Action Keys
Toggle grid on and off. Alt+G
Toggle snap to grid on and off. Alt+P
Increase grid interval by 5 pixels. Alt+Page Up
Decrease grid interval by 5 pixels. Alt+Page Down
Action Keys
Align selected components and groups on Ctrl+Alt+1
their left edges.
Align selected components and groups on Ctrl+Alt+2
their horizontal centers.
19-6
App Designer Keyboard Shortcuts
Action Keys
Align selected components and groups on Ctrl+Alt+3
their right edges.
Align selected components and groups on Ctrl+Alt+4
their top edges.
Align selected components and groups on Ctrl+Alt+5
their vertical middle.
Align selected components and groups on Ctrl+Alt+6
their bottom edges.
19-7
19 Keyboard Shortcuts
19-8
App Designer Keyboard Shortcuts
19-9
19 Keyboard Shortcuts
19-10
App Packaging
11
20
Apps Overview
What Is an App?
A MATLAB app is a self-contained MATLAB program with a user interface that automates
a task or calculation. All the operations required to complete the task — getting data into
the app, performing calculations on the data, and getting results are performed within the
app. Apps are included in many MATLAB products. In addition, you can create your own
apps. The Apps tab on the MATLAB Toolstrip displays all currently installed apps when
you click the down arrow on the far right of the toolstrip.
Note You cannot run MATLAB apps using the MATLAB Runtime. Apps are for MATLAB to
MATLAB deployment. To run code using the MATLAB Runtime, the code must be
packaged using MATLAB Compiler.
• MATLAB Products
You can create your own MATLAB app and package it into a single file that you can
distribute to others. The apps packaging tool automatically finds and includes all the
files needed for your app. It also identifies any MATLAB products required to run your
app.
20-2
Apps Overview
You can share your app directly with other users, or share it with the MATLAB user
community by uploading it to the MATLAB File Exchange. When others install your
app, they do not need to be concerned with the MATLAB search path or other
installation details.
Apps (and other files) uploaded to the MATLAB File Exchange are available from
within MATLAB:
1 On the Home tab, in the Environment section, click the Add-Ons arrow button.
2 Click Get Add-Ons.
3 Search for apps by name or descriptive text.
• Performs a dependency analysis that helps you find and add the files your app
requires.
• Reminds you to add shared resources and helper files.
• Stores information you provide about your app with the app package. This information
includes a description, a list of additional MATLAB products required by your app, and
a list of supported platforms.
• Automates app updates (versioning).
• It is a one-click installation.
• Users do not need to manage the MATLAB search path or other installation details.
• Your app appears alongside MATLAB toolbox apps in the apps gallery.
20-3
20 Packaging GUIs as Apps
• Write the app as an interactive application with a user interface written in the
MATLAB language.
• All interaction with the app is through the user interface.
• Make the app reusable. Do not make it necessary for a user restart the app to use
different data or inputs with it.
• Ensure the main function returns the handle of the main figure. (The main function
created by GUIDE returns the figure handle by default.)
Although not a requirement, doing so enables MATLAB to remove the app files from
the search path when users exit the app.
• If you want to share your app on MATLAB File Exchange, you must release it under a
BSD license. In addition, there are restrictions on the use of binary files such as MEX-
files, p-coded files, or DLLs.
Requirements:
See Also
Related Examples
• “Package Apps From the MATLAB Toolstrip” on page 20-5
• “Modify Apps” on page 20-11
• “Ways to Share Apps” on page 20-13
20-4
Package Apps From the MATLAB Toolstrip
Note As you enter information in the Package Apps dialog box, MATLAB creates and
saves a .prj file continuously. A .prj file contains information about your app, such as
included files and a description. Therefore, if you exit the dialog box before clicking the
Package button, the .prj file remains, even though a .mlappinstall file is not
created. The .prj file enables you to quit and resume the app creation process where
you left off.
1 On the desktop Toolstrip, on the Home tab, click the Add-Ons down-arrow.
2 Click Package App.
3 In the Package App dialog box, click Add main file and specify the file that you use
to run the app you created.
The main file must be callable with no input and must be a function or method, not a
script. MATLAB analyzes the main file to determine if there are other files used in the
app. For more information, see “Dependency Analysis” on page 20-18.
Tip The main file must return the figure handle of your app for MATLAB to remove
your app files from the search path when users exit the app. For more information,
see “What Is the MATLAB Search Path?”
20-5
20 Packaging GUIs as Apps
If you install the app, MATLAB uses the name for the .mlappinstall file and to
label your app in the apps gallery.
b Optionally, specify an app icon.
Click the icon to the left of the App Name field to select an icon for your app or
to specify a custom icon. MATLAB automatically scales the icon for use in the
Install dialog box, App gallery, and quick access toolbar.
c Optionally, select a previously saved screenshot to represent your app.
d Optionally, specify author information.
e In the Description field, describe your app so others can decide if they want to
install it.
f Identify the products on which your app depends.
Click the plus button on the right side of the Products field, select the products
on which your app depends, and then click Apply Changes. Keep in mind that
your users must have all of the dependent products installed on their systems.
After you create the package, when you select a .mlappinstall file in the Current
Folder browser, MATLAB displays the information you provided (except your email
address and company name) in the Current Folder browser Details panel. If you
share your app in the MATLAB Central File Exchange, the same information also
displays there. The screenshot you select, if any, represents your app in File
Exchange.
6 Click Package.
As part of the app packaging process, MATLAB creates a .prj file that contains
information about your app, such as included files and a description. The .prj file
enables you to update the files in your app without requiring you to respecify
descriptive information about the app.
7 In the Build dialog box, note the location of the installation file (.mlappinstall),
and then click Close.
20-6
See Also
See Also
Related Examples
• “Modify Apps” on page 20-11
• “Ways to Share Apps” on page 20-13
• “MATLAB App Installer File — mlappinstall” on page 20-17
• “Dependency Analysis” on page 20-18
20-7
20 Packaging GUIs as Apps
1 In App Designer, select the Designer tab. Then select Share > MATLAB App.
• The application name matches the title assigned to the figure in App Designer.
• The Main file is the MLAPP file you currently have selected for editing.
• The Output folder is the folder that contains the MLAPP file.
• The files listed under Files included through analysis include any files MATLAB
detected as dependent files. You can add additional files by clicking Add files/
folders under Shared resources and helper files.
20-8
See Also
3 Specify details to display in the apps gallery. Enter the appropriate information in
these fields: Author Name, Email, Company, Summary, and Description.
4 In the Products section, select the products that are required to run the app. Keep in
mind that your users must have all of the dependent products installed on their
systems.
5 Click Select screenshot to specify an icon to display in the apps gallery.
6 Click Package to create the .mlappinstall file to share with your users. Later, if
you click the Package App button in the App Designer Toolstrip again, the Package
App dialog box opens the most recently modified .prj file for the MLAPP file.
See Also
Related Examples
• “Package Apps From the MATLAB Toolstrip” on page 20-5
20-9
20 Packaging GUIs as Apps
20-10
Modify Apps
Modify Apps
When you update the files included in a .mlappinstall file, you recreate and overwrite
the original app. You cannot maintain two versions of the same app.
1 In the Current Folder browser, navigate to the folder containing the project file
(.prj) that MATLAB created when you packaged the app.
By default, MATLAB writes the .prj file to the folder that was the current folder
when you packaged the app.
2 From the Current Folder browser, double-click the project file for your app package,
appname.prj
• If you made code changes, add the main file again, and refresh the files included
through analysis.
• If your code calls additional files that are not included through analysis, add them.
• If you want anyone who installs your app over a previous installation to be
informed that the content is different, change the version.
Version numbers must be a combination of integers and periods, and can include
up to three periods — 2.3.5.2, for example.
Anyone who attempts to install a revision of your app over another version is
notified that the version number is changed. The user can continue or cancel the
installation.
• If your changes introduce different product dependencies, adjust the product list
in the Products field. Keep in mind that your users must have all of the
dependent products installed on their systems.
4 Click Package.
20-11
20 Packaging GUIs as Apps
See Also
Related Examples
• “Ways to Share Apps” on page 20-13
• “MATLAB App Installer File — mlappinstall” on page 20-17
• “Dependency Analysis” on page 20-18
20-12
Ways to Share Apps
• “Share MATLAB Files Directly” on page 20-13 — This approach is the simplest way to
share an app, but your users must have MATLAB installed on their systems, as well as
other MathWorks products that your app depends on. They must also be familiar with
executing commands in the MATLAB Command Window and know how to manage the
MATLAB path.
• “Package Your App” on page 20-14 — This approach uses the app packaging tool
provided with MATLAB. When your users install a packaged app, the app appears in
the Apps tab in the MATLAB Toolstrip. This approach is useful for sharing apps with
larger audiences, or when your users are less familiar with executing commands in the
MATLAB Command Window or managing the MATLAB path. As in the case of sharing
MATLAB files directly, your users must have MATLAB installed on their systems (as
well as other MathWorks products that your app depends on).
• “Create a Deployed Web App” on page 20-15 — This approach lets you create apps
that users within an organization can run in their web browsers. To deploy a web app,
you must have MATLAB Compiler installed on your system. Your users must have a
web browser installed that can access your intranet, but they do not need to have
MATLAB installed.
• “Create a Standalone Desktop Application” on page 20-16 — This approach lets you
share desktop apps with users that do not have MATLAB installed on their systems. To
create the standalone application, you must have MATLAB Compiler installed on your
system. To run the application, your users must have MATLAB Runtime installed on
their systems. For more information, see https://www.mathworks.com/products/
compiler/mcr.html.
If you created your app programmatically, share all .m files and other dependent files with
your users.
If you created your app in App Designer, share the .mlapp file and all other dependent
files with your users. To provide a richer file browsing experience for your users, provide
a name, summary, and description by clicking App Details in the Designer tab of the
20-13
20 Packaging GUIs as Apps
App Designer toolstrip. The App Details dialog box also provides an option for specifying
a screen shot. If you do not specify a screen shot, App Designer captures and updates a
screen shot automatically when you run the app.
MATLAB provides your app details to some operating systems for display in their file
browsers. Specifying apps details also makes it easier to package and compile your apps.
The .mlapp file provides those details automatically to those interfaces.
20-14
Ways to Share Apps
You can share the .mlappinstall file directly with your users. To install it, they must
double-click the .mlappinstall file in the MATLAB Current Folder browser.
Alternatively, you can share your app as an add-on by uploading the .mlappinstall file
to MATLAB Central File Exchange. Your users can find and install your add-on from the
MATLAB Toolstrip by performing these steps:
1 In the MATLAB Toolstrip, on the Home tab, in the Environment section, click the
Add-Ons icon.
2 Find the add-on by browsing through available categories on the left side of the Add-
On Explorer window. Use the search bar to search for an add-on using a keyword.
3 Click the add-on to open its detailed information page.
4 On the information page, click Add to install the add-on.
Note Although .mlappinstall files can contain any files you specify, MATLAB Central
File Exchange places additional limitations on submissions. Your app cannot be submitted
to File Exchange when it contains any of the following files:
• MEX-files
• Other binary executable files, such as DLLs or ActiveX controls. (Data and image files
are typically acceptable.)
Once you have MATLAB Compiler on your system, you can open the Web App Compiler
from within App Designer by clicking Share in the Designer tab and selecting Web
App. For more information, see “Web Apps” (MATLAB Compiler).
20-15
20 Packaging GUIs as Apps
Once you have MATLAB Compiler on your system, you can open the Application Compiler
from within App Designer by clicking Share in the Designer tab and selecting
Standalone Desktop App.
If you used GUIDE or created your app programmatically, you can open the Application
Compiler from the MATLAB Toolstrip, on the Apps tab, by clicking the Application
Compiler icon.
See “Create Standalone Application from MATLAB” (MATLAB Compiler) for instructions
on using the Application Compiler.
See Also
Related Examples
• “Apps Overview” on page 20-2
• “Ways to Build Apps” on page 1-2
20-16
MATLAB App Installer File — mlappinstall
See Also
Related Examples
• “Package Apps From the MATLAB Toolstrip” on page 20-5
20-17
20 Packaging GUIs as Apps
Dependency Analysis
When you create an app package, MATLAB analyzes your main file and attempts to
include all the files that your app uses. However, MATLAB does not guarantee to find
every dependent file. It does not find files for functions that your code references as
character vectors (for instance, as arguments to eval, feval, and callback functions). In
addition, MATLAB can include some files that the main file never calls when it runs.
• Executable files, such as MATLAB program files, P-files, Fig-files, and MEX-files.
• Files that your app accesses by calling standard and low-level I/O functions. These
dependent files include text files, spreadsheets, images, audio, video, and XML files.
• Files that your app accesses by calling any of these functions: audioinfo,
audioread, csvread, daqread, dlmread, fileread, fopen, imfinfo,
importdata, imread, load, matfile, mmfileinfo, open, readtable, type,
VideoReader, xlsfinfo, xlsread, xmlread, and xslt.
Dependency analysis does not search for Java classes, .jar files, or files stored in a
scientific format such as NetCDF or HDF. Click Add files/folders in the Package Apps
dialog box to add these types of files manually.
See Also
matlab.codetools.requiredFilesAndProducts
20-18