Creating Graphical User InterfacesVersion 7MATLAB®The Language of Technical Computing
x ContentsCallback Syntax and Arguments . . . . . . . . . . . . . . . . . . . . . . . 8-11Naming of Callback Functions . . . . . . . . . . . . . .
6 Laying Out a GUI6-10You can select other plots in the pop-up menu. Clicking the Update button displays the currently selected plot on the axes.The G
Selecting a GUI Template6-11Running the GUI displays the dialog box shown in the following figure:The GUI returns the text string Yes or No, depending
6 Laying Out a GUI6-12Setting the GUI SizeSet the size of the GUI by resizing the grid area in the Layout Editor. Click on the lower-right corner and
Setting the GUI Size6-133 In the Property Inspector, click the + sign next to Position. The elements of the component’s Position property are displaye
6 Laying Out a GUI6-14Adding Components to the GUI• “Available Components” on page 6-14• “Adding Components to the Layout Area” on page 6-18• “Assigni
Adding Components to the GUI6-15When you first open the Layout Editor, the component palette contains only icons. To display the names of the GUI comp
6 Laying Out a GUI6-16 Component DescriptionPush Button Push buttons generate an action when clicked. For example, an OK button might apply settings a
Adding Components to the GUI6-17Slider Sliders accept numeric input within a specific range by enabling the user to move a sliding bar, which is calle
6 Laying Out a GUI6-18Adding Components to the Layout AreaThis topic tells you how to place components in the layout area and give each component a un
Adding Components to the GUI6-19the upper-left corner of the component to be, then setting the size of the control by dragging the cursor to the lower
xi10Examples of GUIDE GUIsGUI with Multiple Axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2Techniques Used in the Example .
6 Laying Out a GUI6-20 Adding a Component to a Panel or Button GroupTo add a component to a panel or button group, select the component in the compo
Adding Components to the GUI6-21 If the component is not entirely contained in the panel or button group, it appears to be clipped in the layout edito
6 Laying Out a GUI6-22You can use the Object Browser to determine the child objects of a panel or button group. “Viewing the Object Hierarchy” on page
Adding Components to the GUI6-231 Select the desired ActiveX control. The right panel shows a preview of the selected control.2 Click Create, the cont
6 Laying Out a GUI6-24See “ActiveX Control” on page 8-31 for information about programming a sample ActiveX control and an example.Assigning an Identi
Adding Components to the GUI6-25Adding Text to the ComponentsMany components have labels, lists, or other text that distinguishes them. You can set th
6 Laying Out a GUI6-262 The component label changes when you click outside the String field.Pop-Up MenuPop-up menus display a list of choices.1 In the
Adding Components to the GUI6-271 In the Property Inspector, click the button next to String. In the String dialog box that displays, replace the exis
6 Laying Out a GUI6-281 In the Property Inspector, click the button next to String. In the String dialog box that displays, type the text that you wan
Adding Components to the GUI6-292 The list appears in the list box in the Layout Area with the top-most item selected.3 If the list box is not large e
xii ContentsThe Contact Name Callback . . . . . . . . . . . . . . . . . . . . . . . . . . 10-38The Contact Phone Number Callback . . . . . . . . . .
6 Laying Out a GUI6-30and Min properties so that Max-Min>1. For example, Max=2, Min = 0.- Set the Value property to the index of the item you want
Adding Components to the GUI6-313 If you want to change the position of the title, select the button next to TitlePosition in the Property Inspector,
6 Laying Out a GUI6-32• Press Ctrl+A to select all child objects of the figure. This does not select components that are child objects of panels or bu
Adding Components to the GUI6-33clipboard to the location of the last mouse click. It positions the upper left corner of the contents at the mouse cli
6 Laying Out a GUI6-34• Bring to Front — move the selected object(s) in front of nonselected objects (available from the right-click context menu, the
Adding Components to the GUI6-35Dragging ComponentsSelect one or more components that you want to move, then drag them to the desired position and dro
6 Laying Out a GUI6-362 Click the + sign next to Position. The Property Inspector displays the elements of the Position property.3 If you have selecte
Adding Components to the GUI6-37Resizing ComponentsYou can resize components in one of the following ways:• “Dragging a Corner of the Component” on pa
6 Laying Out a GUI6-383 Type the width and height you want the components to be.4 Reset the Units property to characters.5 Reset the Units property to
Aligning Components6-39Aligning ComponentsThe Layout Editor provides a number of features that facilitate alignment and distribution of components wit
xiiiCreating GUIs Programmatically11Functions for Creating GUIsIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6 Laying Out a GUI6-40The alignment tool provides two types of alignment operations:•Align — align all selected components to a single reference line.
Aligning Components6-41All of the align options (vertical top, center, bottom and horizontal left, center, right) place the selected components with r
6 Laying Out a GUI6-42from left, distance from bottom, height, width]. The values are given in the units specified by the Units property of the compon
Aligning Components6-43Use the Grid and Rulers dialog (select Grid and Rulers from the Tools menu) to:• Control visibility of rulers, grid, and guide
6 Laying Out a GUI6-44Guide lines used for horizontal alignmentClick on the top or left ruler and drag the guide to the desired positionGuide line use
Setting Tab Order6-45Setting Tab OrderA GUI’s tab order is the order in which components of the GUI are selected when a user presses the Tab key on th
6 Laying Out a GUI6-46To examine and change the tab order of the panel components, click the panel background to select it, then select Tab Order Edit
Setting Tab Order6-47arrow to move the component up or down in the list. If you set the tab order for the three components in the example to be 1 Surf
6 Laying Out a GUI6-48Creating MenusGUIDE enables you to create two kinds of menus:• “Menus for the Menu Bar” on page 6-49 — drop-down menus whose tit
Creating Menus6-49Note In general, programming conventions described for components in Chapter 8, “Programming the GUI” also apply to menu items. See
xiv ContentsTechniques Used in the Example . . . . . . . . . . . . . . . . . . . . . . . . . 25View the Completed GUI M-File . . . . . . . . . . . .
6 Laying Out a GUI6-50Note By default, GUIDE selects the Menu Bar tab when you open the Menu Editor.2 Click on the menu title to display a selection
Creating Menus6-51Adding Items to a MenuUse the New Menu Item tool to create menu items that are displayed in the drop-down menu.1 Add an Open menu it
6 Laying Out a GUI6-52You can also: • Choose a keyboard accelerator for the menu item with the Accelerator pop-up menu. In combination with Ctrl, this
Creating Menus6-53this field, GUIDE automatically sets the value using a combination of the Tag field and the GUI filename. See “Menu Item” on page 8-
6 Laying Out a GUI6-54Note See “Menu Item” on page 8-37 for information about programming menu items.Laying Out Three MenusThe following Menu Editor
Creating Menus6-55When you run the GUI, the menu titles appear in the menu bar.
6 Laying Out a GUI6-56Context MenusA context menu is displayed when a user right-clicks on the object for which the menu is defined. The Menu Editor e
Creating Menus6-57Adding Items to the Context MenuUse the New Menu Item tool to create menu items that are displayed in the context menu.1 Add a Blue
6 Laying Out a GUI6-582 Fill in the Label and Tag fields for the new menu item. For example, set Label to 'Blue background color' and set Ta
Creating Menus6-59• Display a check next to the menu item when the menu is first opened by checking Check mark this item. A check indicates the curren
Getting StartedThese sections show you how to create a simple graphical user interface (GUI) using GUIDE, the MATLAB® graphical user interface develop
6 Laying Out a GUI6-60In the GUI M-file, complete the callback subfunction for each item in the context menu. Each callback executes when a user selec
Creating Toolbars6-61Creating ToolbarsGUIDE provides no tool to enable you do add a toolbar. However, you can add a toolbar by adding code to the open
6 Laying Out a GUI6-62Viewing the Object HierarchyThe Object Browser displays a hierarchical list of the objects in the figure, including both compone
Designing for Cross-Platform Compatibility6-63Designing for Cross-Platform CompatibilityYou can create GUIs that behave more consistently when run on
6 Laying Out a GUI6-64Specifying a Fixed-Width FontIf you want to use a fixed-width font for a user interface control (uicontrol), set its FontName pr
Designing for Cross-Platform Compatibility6-65systems, e.g., the standard shade of gray on the PC differs from that on UNIX, and may not match the def
6 Laying Out a GUI6-66Cross-Platform Compatible UnitsCross-platform compatible GUIs should look correct on computers having different screen sizes and
Designing for Cross-Platform Compatibility6-67Units property back to characters, and the components’ Units properties to characters (nonresizable GUIs
6 Laying Out a GUI6-68
7Saving and Running the GUINaming a GUI and Its Files (p. 7-2) Describes the GUI files and how they are named.Saving a GUI (p. 7-5) Describes the var
7 Saving and Running the GUI7-2Naming a GUI and Its Files• “The GUI Files” on page 7-2• “File and GUI Names” on page 7-3• “How to Assign Names” on pag
Naming a GUI and Its Files7-3File and GUI NamesThe M-file and the FIG-file that define your GUI must have the same name. This name is also the name of
7 Saving and Running the GUI7-4- By selecting the Save or Save as options on the File menuGUIDE prompts you for a name before saving the GUI.• The fir
Saving a GUI7-5Saving a GUIThis section tells you how to save a GUI you have constructed in GUIDE.• “Ways to Save a GUI” on page 7-5• “Saving a New GU
7 Saving and Running the GUI7-6• Clicking the Save icon on the Layout Editor toolbar• Selecting the Save or Save as options on the File menu• Clicki
Saving a GUI7-7Note that button groups and panels are introduced in MATLAB 7.0, and you should not use them in GUIs that you expect to run in earlier
7 Saving and Running the GUI7-83 Change the directory if you choose, and then enter the name you want to use for the FIG-file. Be sure to choose a wri
Saving a GUI7-96 If you chose Yes in the previous step, GUIDE displays a dialog that asks if you want to replace the existing M-file or append to it.
7 Saving and Running the GUI7-10Running a GUIGenerally, you run your GUI by executing the M-file that GUIDE generates. This M-file contains the comman
Running a GUI7-11If a GUI accepts arguments when it is run, they are passed to the GUI’s opening function. See “Opening Function” on page 8-15 for mor
1About GUIs in MATLABWhat Is a GUI? (p. 1-2) Explains a graphical user interface (GUI) from a GUI user’s perspective.How Does a GUI Work? (p. 1-3) Ex
7 Saving and Running the GUI7-12Saving and Displaying Only the GUI Layout• “Saving a GUI Layout Only” on page 7-12• “Displaying a GUI Layout Only” on
Saving and Displaying Only the GUI Layout7-13open('mygui.fig')openfig('mygui')hgload('mygui')You can run a GUI that has
7 Saving and Running the GUI7-14
8Programming the GUICallbacks: An Overview (p. 8-2) Introduces the functions, referred to as callbacks, that you use to program GUI behavior. GUI Fil
8 Programming the GUI8-2Callbacks: An OverviewAfter you have laid out your GUI, you need to program its behavior. The code you write controls how the
Callbacks: An Overview8-3Each kind of callback has a triggering mechanism or event that causes it to be called. The following table lists the callback
8 Programming the GUI8-4Note User interface controls include push buttons, sliders, radio buttons, check boxes, editable text boxes, static text boxe
GUI Files: An Overview8-5GUI Files: An Overview• “M-Files and FIG-Files” on page 8-5• “GUI M-File Structure” on page 8-6• “Adding Callback Templates t
8 Programming the GUI8-6GUI M-File Structure The GUI M-file that GUIDE generates is a function file. The name of the main function is the same as the
GUI Files: An Overview8-7Adding Callback Templates to an Existing GUI M-FileWhen you save the GUI, GUIDE automatically adds templates for some callbac
1 About GUIs in MATLAB1-2What Is a GUI?A graphical user interface (GUI) is a graphical display that contains devices, or components, that enable a use
8 Programming the GUI8-8Associating Callbacks with ComponentsA GUI can have many components and GUIDE provides a way of specifying which callback shou
Associating Callbacks with Components8-9-When you save the GUI, GUIDE constructs the name of the callback by appending an underscore (_) and the name
8 Programming the GUI8-10See “Input Arguments” on page 8-13 for information about the callback input arguments.When you save the GUI, GUIDE also opens
Callback Syntax and Arguments8-11Callback Syntax and ArgumentsGUIDE defines conventions for callback syntax and arguments and implements these convent
8 Programming the GUI8-12When GUIDE generates the template, it creates the callback name by appending an underscore (_) and the name of the callback p
Callback Syntax and Arguments8-13• References in the M-file to the field of the handles structure that contains the component’s handle. See “The Handl
8 Programming the GUI8-14handles = figure1: 160.0011 edit1: 9.0020 uipanel1: 8.0017 popupmenu1: 7.0018 pushbutton1: 161.
Initialization Callbacks8-15Initialization CallbacksGUIDE automatically includes two callbacks, the opening function and the output function, in every
8 Programming the GUI8-16% Choose default command line output for myguihandles.output = hObject; % Update handles structureguidata(hObject, handles);
Initialization Callbacks8-17• handles.output = hObject adds a new element, output, to the handles structure and assigns it the value of the input argu
How Does a GUI Work?1-3How Does a GUI Work?Each component, and the GUI itself, is associated with one or more user-written routines known as callbacks
8 Programming the GUI8-18% Get default command line output from handles structurevarargout{1} = handles.output;Input ArgumentsThe output function has
Examples: Programming GUI Components8-19Examples: Programming GUI ComponentsThis section provides basic code examples to get you started programming t
8 Programming the GUI8-20function pushbutton1_Callback(hObject, eventdata, handles)display Goodbyedelete(handles.figure1);Adding an Image to a Push Bu
Examples: Programming GUI Components8-21elseif button_state == get(hObject,'Min')% Toggle button is not pressed-take appropriate action .
8 Programming the GUI8-22function checkbox1_Callback(hObject, eventdata, handles)if (get(hObject,'Value') == get(hObject,'Max'))%
Examples: Programming GUI Components8-23Triggering Callback ExecutionFor both UNIX and Windows, clicking inside the GUI but outside the edit text caus
8 Programming the GUI8-24function listbox1_Callback(hObject, eventdata, handles)index_selected = get(handles.listbox1,'Value');list = get(ha
Examples: Programming GUI Components8-25is fixed, then you can use this approach. Else, you can use the index to retrieve the actual string for the se
8 Programming the GUI8-26Note To set Resize behavior for the figure to Other (Use ResizeFcn), select GUI Options from the Layout Editor Tools menu. 1
Examples: Programming GUI Components8-27For radio buttons and toggle buttons that are managed by a button group, you must include the code to control
How to Contact The MathWorks:www.mathworks.com Webcomp.soft-sys.matlab Newsgroup www.mathworks.com/contact_TS.html Technical support suggest@mathwor
1 About GUIs in MATLAB1-4Where Do I Start?First you have to design your GUI. You have to decide what you want it to do, how you want the user to inter
8 Programming the GUI8-28plotting of a graph to an axes. In this case, the button’s Callback callback contains the code that generates the plot.This e
Examples: Programming GUI Components8-29Plotting to a GUI with Multiple AxesIf a GUI has multiple axes, explicitly specify which axes you want to targ
8 Programming the GUI8-302 Add this code to the Plot 2 push button’s Callback callback. The contour function displays the contour plot of a matrix, in
Examples: Programming GUI Components8-31default). From the Layout Editor select Tools -> GUI Options -> Command Line Accessibility: Callback. Se
8 Programming the GUI8-322 Activate the GUI by clicking the Run icon on the toolbar and save the GUI when prompted. GUIDE displays the GUI shown in
Examples: Programming GUI Components8-333 View the ActiveX Properties with the Property Inspector. Select the control in the Layout Editor, and then s
8 Programming the GUI8-34If you click the GUI enough times, the circle disappears entirely.Programming a User Interface Control to Update an ActiveX C
Examples: Programming GUI Components8-35handles.default_radius = handles.activex1.radius;3 In the activex1_Click callback, reset the slider’s Value ea
8 Programming the GUI8-36at the MATLAB prompt. This displays the available methods in a new window, as shown in the following figure.Alternatively, yo
Examples: Programming GUI Components8-37Compiling a GUI that Contains an ActiveX ControlIf you use the MATLAB Compiler mcc command to compile a GUI th
2Creating a GUI with GUIDEGUIDE: A Brief Introduction (p. 2-2) Introduces GUIDE, the graphical user interface development environment.The Example: Si
8 Programming the GUI8-38When a user selects the to file option under the Edit menu’s Copy option, only the to file callback is required to perform th
Examples: Programming GUI Components8-39Note From the Menu Editor, you can view a menu item’s Callback callback in your editor by selecting the menu
8 Programming the GUI8-40
9Managing Application-Defined DataMechanisms for Managing Data (p. 9-2)Describes various mechanisms for managing application-defined data. Explains h
9 Managing Application-Defined Data9-2Mechanisms for Managing DataMost GUIs generate or use data that is specific to the application. This topic descr
Mechanisms for Managing Data9-3GUI data provides application developers with a convenient interface to a figure’s application data:• You do not need t
9 Managing Application-Defined Data9-42 Use the following command to save the data.guidata(hObject,handles)where hObject is the handle of the componen
Mechanisms for Managing Data9-5The following table summarizes the functions that provide access to application data. For more detailed information, se
9 Managing Application-Defined Data9-61 Use getappdata to retrieve the structure. From the example in the previous topic, the name of the application
Sharing Data Among a GUI’s Callbacks9-7Sharing Data Among a GUI’s CallbacksYou can use GUI data, application data, and the UserData property to share
2 Creating a GUI with GUIDE2-2GUIDE: A Brief IntroductionGUIDE, the MATLAB Graphical User Interface development environment, provides a set of tools f
9 Managing Application-Defined Data9-8The GUI behavior is as follows:• When a user moves the slider, the text box displays the slider’s current value.
Sharing Data Among a GUI’s Callbacks9-93 Set the slider value from the edit text Callback callback. The edit text Callback sets the slider’s value to
9 Managing Application-Defined Data9-10functions setappdata, getappdata, isappdata, and rmappdata to manage application data.See “Application Data” on
Sharing Data Among a GUI’s Callbacks9-11% Retrieve and increment the error count.slider_data = getappdata(handles.figure1,'slider');slider_d
9 Managing Application-Defined Data9-122 Set the edit text value from the slider Callback callback. Add this statement to the slider Callback.set(hand
10Examples of GUIDE GUIsGUI with Multiple Axes (p. 10-2) Analyze data and generate frequency and time domain plots in the GUI figure.List Box Directo
10 Examples of GUIDE GUIs10-2GUI with Multiple AxesThis example creates a GUI that contains two axes for plotting data. For simplicity, this example o
GUI with Multiple Axes10-3View Completed Layout and Its GUI M-FileIf you are reading this in the MATLAB Help browser, you can click the following link
10 Examples of GUIDE GUIs10-4To create the default values, set the String property of the edit text. The following figure shows the value set for the
GUI with Multiple Axes10-5For example, the Tag of the axes used to display the FFT is set to frequency_axes. Therefore, within a callback, you access
The Example: Simple GUI2-3The Example: Simple GUIThis chapter shows you how to use GUIDE to create the example graphical user interface (GUI) which is
10 Examples of GUIDE GUIs10-6like you would on the command line. Note that Callback is the default setting for command-line accessibility.See “GUI Opt
GUI with Multiple Axes10-7• Making the appropriate axes current using the axes command and the handle of the axes. For example,axes(handles.frequency_
10 Examples of GUIDE GUIs10-8plot(t,x)set(handles.time_axes,'XMinorTick','on')grid on
List Box Directory Reader10-9List Box Directory ReaderThis example uses a list box to display the files in a directory. When the user double clicks on
10 Examples of GUIDE GUIs10-10Note The following links execute MATLAB commands and are designed to work within the MATLAB Help browser. If you are re
List Box Directory Reader10-11• First input argument is not a directory, but is a character string and there is more than one argument — execute the s
10 Examples of GUIDE GUIs10-12% Populate the listboxload_listbox(initial_dir,handles)Loading the List BoxThis example creates a subfunction to load it
List Box Directory Reader10-13guidata(handles.figure1,handles)set(handles.listbox1,'String',handles.file_names,...'Value',1)set(ha
10 Examples of GUIDE GUIs10-14• If the selection is a file — get the file extension (fileparts) to determine if it is a FIG-file, which is opened with
List Box Directory Reader10-15does not take this approach for FIG-files since openfig.m is required by the GUI M-file. See open for more information.
2 Creating a GUI with GUIDE2-4Laying Out a Simple GUI• “Opening a New GUI in the Layout Editor” on page 2-4• “Setting the GUI Figure Size” on page 2-6
10 Examples of GUIDE GUIs10-16Accessing Workspace Variables from a List BoxThis GUI uses a list box to display workspace variables, which the user can
Accessing Workspace Variables from a List Box10-17View Completed Layout and Its GUI M-FileIf you are reading this in the MATLAB Help browser, you can
10 Examples of GUIDE GUIs10-18Enabling Multiple SelectionTo enable multiple selection in a list box, you must set the Min and Max properties so that M
Accessing Workspace Variables from a List Box10-19Callbacks for the Plotting ButtonsThe callbacks for the plotting buttons call get_var_names to get t
10 Examples of GUIDE GUIs10-20A GUI to Set Simulink Model Parameters This example illustrates how to create a GUI that sets the parameters of a Simuli
A GUI to Set Simulink Model Parameters10-21all component properties and to understand how the components are assembled to create the GUI. You can also
10 Examples of GUIDE GUIs10-22Running the SimulationOnce you have set the gain values, you can run the simulation by clicking the Simulate and store r
A GUI to Set Simulink Model Parameters10-23• Determine if the model is open (find_system).• Open the block diagram for the model and the subsystem whe
10 Examples of GUIDE GUIs10-24• Calls model_open to ensure that the Simulink model is open so that simulation parameters can be set.• Gets the new sli
A GUI to Set Simulink Model Parameters10-25Here is the callback for the Kf Current value text box.function KfCurrentValue_Callback(hObject, eventdata,
Laying Out a Simple GUI2-53 Display the names of the GUI components in the component palette. Select Preferences from the MATLAB File menu. Then selec
10 Examples of GUIDE GUIs10-26Here is the Simulate and store results button callback.function SimulateButton_Callback(hObject, eventdata, handles)[tim
A GUI to Set Simulink Model Parameters10-27set(handles.ResultsList,'String',ResultsStr);% Store the new ResultsDatahandles.ResultsData = Res
10 Examples of GUIDE GUIs10-28% Store the new ResultsDataguidata(hObject, handles)Plotting the Results DataThe GUI Plot button callback creates a plot
A GUI to Set Simulink Model Parameters10-29% Get data to plot and generate command string with color% specifiedlegendStr = cell(length(currentVal),1);
10 Examples of GUIDE GUIs10-30• The which command returns the full path to the file when it is on the MATLAB path• The web command displays the file i
A GUI to Set Simulink Model Parameters10-31In this case, there is no need for the list box callback to execute, so you should delete it from the GUI M
10 Examples of GUIDE GUIs10-32An Address Book ReaderThis example shows how to implement a GUI that displays names and phone numbers, which it reads fr
An Address Book Reader10-33• An index pointer that indicates the current name and phone number, which must be updated as the user pages through the ad
10 Examples of GUIDE GUIs10-34• GUI M-file options selected: - Generate callback function prototypes- Application allows only one instance to runCalli
An Address Book Reader10-35 & the second element is a MATLAB file, then load that fileelseif (length(varargin) == 2 && ... strcmp
2 Creating a GUI with GUIDE2-6Setting the GUI Figure SizeSet the size of the GUI by resizing the grid area in the Layout Editor. Click on the lower-ri
10 Examples of GUIDE GUIs10-36Check_And_Load Code ListingThis is the Check_And_Load function.function pass = Check_And_Load(file,handles)% Initialize
An Address Book Reader10-37guidata(handles.Address_Book,handles)elseerrordlg('Not a valid Address Book','Address Book Error')endTh
10 Examples of GUIDE GUIs10-38The Contact Name CallbackThe Contact Name text box displays the name of the address book entry. If you type in a new nam
An Address Book Reader10-39set(handles.Contact_Name,'string',Addresses(i).Name)set(handles.Contact_Phone,'string',Addresses(i).Pho
10 Examples of GUIDE GUIs10-40dialog. Both the current address book and the index pointer are saved in the handles structure so that this data is avai
An Address Book Reader10-41Determining Which Button Is ClickedThe callback defines an additional argument, str, that indicates which button, Prev or N
10 Examples of GUIDE GUIs10-42% If the index is less than one then set it equal to the index % of the last element in the Addresses arrayif i <
An Address Book Reader10-43the Contact_Name_Callback or the Contact_Phone_Callback updates handles.Addresses.Saving the MAT-FileIf the user selects Sa
10 Examples of GUIDE GUIs10-44save(File,'Addresses')handles.LastFile = File;guidata(hObject, handles)endendThe Create New MenuThe Create New
An Address Book Reader10-45Changing the WidthIf the new width is greater than the original width, set the figure to the new width. The size of the Con
Laying Out a Simple GUI2-7Adding the Components1 Add the three push buttons to the GUI. For each push button, select the push button from the componen
10 Examples of GUIDE GUIs10-46Original_Size = [ 0 0 94 19.230769230769234];% If the resized figure is smaller than the % original figure size then com
Using a Modal Dialog to Confirm an Operation10-47Using a Modal Dialog to Confirm an OperationThis example illustrates how to use the modal dialog GUI
10 Examples of GUIDE GUIs10-48Note The following links execute MATLAB commands and are designed to work within the MATLAB Help browser. If you are re
Using a Modal Dialog to Confirm an Operation10-49Setting Up the GUI with the Close ButtonTo set up the second GUI with a Close button, do the followin
10 Examples of GUIDE GUIs10-50% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (se
Using a Modal Dialog to Confirm an Operation10-51Clicking the Yes button closes both the close dialog and the GUI that calls it. Clicking the No butto
10 Examples of GUIDE GUIs10-52- Updates the output field in the handles structure- Executes uiresume to return control to the opening function where u
Creating GUIs ProgrammaticallyThis section provides examples of graphical user interfaces (GUIs) created programmatically.Note Following the release
11Functions for Creating GUIsIntroduction (p. 11-2) Introduces the topic.Function Summary (p. 11-3) Summarizes MATLAB functions specifically intended
2 Creating a GUI with GUIDE2-82 Add the remaining components to the GUI. - A static text- A pop-up menu- An axesArrange the components as shown in the
11 Functions for Creating GUIs11-2IntroductionMATLAB provides a selection of functions for creating GUIs. Some of these create standard dialog boxes w
Function Summary11-3Function Summary• “Predefined Dialog Boxes” on page 11-3• “Creating Components” on page 11-3• “ActiveX Controls” on page 11-4• “Us
11 Functions for Creating GUIs11-4ActiveX ControlsUsing Application-Defined DataInteractive User InputWorking with Preferencesuitoggletool Toggle butt
Function Summary11-5Utilitiessetpref Set preferenceuigetpref Open dialog box for retrieving preferencesuisetpref Manage preferences used in uigetprefa
11 Functions for Creating GUIs11-6
12Examples of GUIs Created ProgrammaticallyIntroduction (p. 12-8) Introduces the examples and lists the programming techniques they illustrate.GUI wi
12 Examples of GUIs Created Programmatically12-8IntroductionThis chapter provides three examples that illustrate the application of certain techniques
GUI with Axes, Menu, and Toolbar12-9GUI with Axes, Menu, and ToolbarThe initial topics introduce the example and the techniques it illustrates:• “The
12 Examples of GUIs Created Programmatically12-10You can select other plots in the pop-up menu. Clicking the Update button displays the currently sele
GUI with Axes, Menu, and Toolbar12-11Techniques Used in the ExampleThis example illustrates the following techniques:• Passing input arguments to the
Laying Out a Simple GUI2-9Aligning the ComponentsYou can use the Alignment Tool to align components with respect to one another, if they have the same
12 Examples of GUIs Created Programmatically12-12mOutputArgs = {}; % Variable for storing output when GUI returnsmPlotTypes is a 5-by-2 cell array th
GUI with Axes, Menu, and Toolbar12-13• The figure function creates the GUI figure.• Setting the MenuBar and Toolbar properties to none, prevents the s
12 Examples of GUIs Created Programmatically12-14Note If you specify the Units property, then the Position property, and any other properties that de
GUI with Axes, Menu, and Toolbar12-15• The uicontrol function creates various user interface controls based on the value of the Style property. This s
12 Examples of GUIs Created Programmatically12-16Here, setting the Parent property of the File menu to hMainFigure makes it the child of the main figu
GUI with Axes, Menu, and Toolbar12-17• The uipushtool TooltipString property assigns a tool tip that displays when the GUI user moves the mouse pointe
12 Examples of GUIs Created Programmatically12-18Defining the CallbacksThis topic defines the callbacks that service the components of the GUI. Becaus
GUI with Axes, Menu, and Toolbar12-19Note MATLAB automatically passes hUpdateButtonCallback two arguments, hObject and eventdata, because the Update
12 Examples of GUIs Created Programmatically12-20Print Menu Item CallbackThe hPrintMenuitemCallback function services the Print menu item and the Prin
GUI with Axes, Menu, and Toolbar12-21 if strcmp(selection,'No') return; end delete(hMainFigure);endThe hCloseMenuitemCallbac
Revision HistoryNovember 2000 Online only New for MATLAB 6.0 (Release12)June 2001 Online only Revised for MATLAB 6.1 (Release 12.1)July 2002 Online on
2 Creating a GUI with GUIDE2-104 Click OK. Your GUI now looks like this is the Layout Editor.
12 Examples of GUIs Created Programmatically12-22Color PaletteThe color palette example includes these topics: • “The Example” on page 12-22• “Techniq
Color Palette12-23The ComponentsThe colorPalette includes the following components:• An array of color cells defined as toggle buttons• An Eraser togg
12 Examples of GUIs Created Programmatically12-24- Displays the selected color in the preview area.- The red, green, and blue values for the newly sel
Color Palette12-25The colorPalette function accepts property value pairs as input arguments. Only the custom property Parent is supported. This proper
12 Examples of GUIs Created Programmatically12-26Note The following link executes MATLAB commands and is designed to work within the MATLAB Help brow
Color Palette12-27Note Three eventdata fields are defined for use with button groups (uibuttongroup). These fields enable you to determine the previo
12 Examples of GUIs Created Programmatically12-282 Data creation. Because the example uses nested functions, defining this data at the top level makes
Color Palette12-29Passing Input Arguments to a GUIInputs to the GUI are custom property/value pairs. colorPalette allows one such property: Parent. Th
12 Examples of GUIs Created Programmatically12-302 If it finds a match, processUserInputs assigns the value that was input for the property to its var
Color Palette12-31Just before returning, colorPalette assigns mOutputArgs the function handle for its getSelectedColor helper function and then assign
Laying Out a Simple GUI2-11Adding Text to the ComponentsAlthough the push buttons, pop-up menu, and static text show some text in the Layout Editor, t
12 Examples of GUIs Created Programmatically12-32 % update color of the selected block mIconCData(y, x,:) = color; localUpdateIco
Icon Editor12-33Icon EditorThe icon editor example includes these topics: • “The Example” on page 12-33• “Techniques Used in the Example” on page 12-3
12 Examples of GUIs Created Programmatically12-34The ComponentsThe GUI includes the following components:• A edit text that instructs the user or cont
Icon Editor12-353 Erase the color in some squares.- Click the Eraser button on the palette- Click in specific squares to erase those squares- Click an
12 Examples of GUIs Created Programmatically12-36Note The following links execute MATLAB commands and are designed to work within the MATLAB Help bro
Icon Editor12-37The example also includes the helper functions listed in the following table.M-File StructureThe iconEditor is programmed using nested
12 Examples of GUIs Created Programmatically12-383 GUI figure and component creation.4 Command line input processing.5 GUI initialization.6 Block exec
Icon Editor12-39Returning Only After the User Makes a ChoiceAt the end of the initialization code, and just before returning, iconEditor calls uiwait
12 Examples of GUIs Created Programmatically12-40Passing Input Arguments to a GUIInputs to the GUI are custom property/value pairs. iconEdit allows th
Icon Editor12-411 processUserInputs sequences through the inputs, if any, and tries to match each property name to a string in the first column of the
2 Creating a GUI with GUIDE2-122 In the layout area select the top push button by clicking it.3 In the Property Inspector, select the String property
12 Examples of GUIs Created Programmatically12-42% different platforms prepareLayout(hMainFigure);prepareLayout first uses findall to retrieve the han
Icon Editor12-43Background Color. The default component background color is the standard system background color on which the GUI is running. This col
12 Examples of GUIs Created Programmatically12-44Character units are defined by characters from the default system font. The width of a character unit
Icon Editor12-45function color = getSelectedColor% function returns the currently selected color in this% colorPlatte color = mSelectedColor;The ic
12 Examples of GUIs Created Programmatically12-46iconEditor calls prepareLayout with the handle of the main figure, in the initialization section of t
Icon Editor12-47height of a character unit is the distance between the baselines of two lines of text. Note that character units are not square.
12 Examples of GUIs Created Programmatically12-48
Index-1IndexAActiveX controlsadding to layout 6-22programming 8-31aligning componentsin GUIDE 6-39Alignment ToolGUIDE 6-39application dataappdata func
IndexIndex-2cross-platform compatibilityGUI background color 6-64GUI design 6-63GUI fonts 6-63GUI units 6-66Ddatasharing among GUI callbacks 9-7defaul
IndexIndex-3GUI object hierarchyviewing in GUIDE 6-62GUI options (GUIDE)function prototypes 5-11singleton 5-11system color background 5-11GUI sizesett
Laying Out a Simple GUI2-134 The push button label changes to Surf when you click outside the String field.5 Select each of the remaining push buttons
IndexIndex-4M-filegenerated by GUIDE 5-11moving componentsin GUIDE 6-34Nnaming a GUIin GUIDE 7-2OObject Browser (GUIDE) 6-62opening .fig files 10-14op
2 Creating a GUI with GUIDE2-143 Replace the existing text with the names of the three data sets: Peaks, Membrane, and Sinc. Press Enter to move to th
Laying Out a Simple GUI2-152 In the Property Inspector, click the button next to String. In the String dialog box that displays, replace the existing
2 Creating a GUI with GUIDE2-16The Completed LayoutIn the Layout Editor, your GUI now looks like this and the next step is to save the layout. The nex
Saving the GUI Layout2-17Saving the GUI LayoutWhen you save a GUI, GUIDE creates two files, a FIG-file and an M-file. The FIG-file, with extension .fi
2 Creating a GUI with GUIDE2-18working directory to the directory containing the GUI files, or adding that directory to the top or bottom of the MATLA
Programming the GUI2-19Programming the GUIWhen you saved your GUI in the previous topic, “Saving the GUI Layout” on page 2-17, GUIDE created two files
2 Creating a GUI with GUIDE2-20The cursor moves to the opening function which already contains this code:% --- Executes just before simple_gui is made
Programming the GUI2-21% Create the data to plot.handles.peaks=peaks(35);handles.membrane=membrane;[x,y] = meshgrid(-8:.5:8);r = sqrt(x.^2+y.^2) + eps
2 Creating a GUI with GUIDE2-22index of the selected string. The pop-up menu callback reads the pop-up menu Value property to determine what item is c
Programming the GUI2-23It then uses a switch statement to make the selected data set the current data. The last statement saves the changes to the han
2 Creating a GUI with GUIDE2-24The GUI M-file opens in the editor if it is not already open, and the cursor moves to the Surf push button callback whi
Programming the GUI2-25 % Display contour plot of the currently selected data. contour(handles.current_data);4 Save the M-file by selecting Save fro
2 Creating a GUI with GUIDE2-26Running the GUIIn the previous topic, you programmed the pop-up menu and the push buttons. You also created data for th
Running the GUI2-273 Try some of the other combinations before closing the GUI.
2 Creating a GUI with GUIDE2-28
3Creating a GUI ProgrammaticallyThe Example: Simple GUI (p. 3-2) Describes the example to be constructed.Function Summary (p. 3-4) Lists the function
vContentsGetting Started1About GUIs in MATLABWhat Is a GUI? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2How D
3 Creating a GUI Programmatically3-2The Example: Simple GUIThis chapter shows you how to write a script that creates the example graphical user interf
The Example: Simple GUI3-3Subsequent topics guide you through the process of creating the GUI. This process begins with “Creating a GUI M-File” on pag
3 Creating a GUI Programmatically3-4Function SummaryMATLAB provides a suite of functions for creating GUIs. This topic introduces you to the functions
Function Summary3-5sinSine; result in radians.sqrtSquare root.surf3-D shaded surface plot.Function Description
3 Creating a GUI Programmatically3-6Creating a GUI M-FileStart by creating an M-file for the example GUI.1 At the MATLAB prompt, type edit. MATLAB ope
Laying Out a Simple GUI3-7Laying Out a Simple GUIThis topic illustrates the basic steps for laying out a GUI.• “Creating the Figure” on page 3-7• “Add
3 Creating a GUI Programmatically3-8These statements use the uicontrol function to create the push buttons. Each statement uses a series of property/v
Laying Out a Simple GUI3-95 Make your GUI visible by adding this command following the align command.set(f,'Visible','on')6 This i
3 Creating a GUI Programmatically3-108 Type help simple_gui at the command line. MATLAB displays this help text.help simple_gui SIMPLE_GUI Select a d
Initializing the GUI3-11Initializing the GUIWhen you make the GUI visible, it should be initialized so that it is ready for the user. This topic shows
vi ContentsGenerating Data to Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19Programming the Pop-Up Menu . . . . . . . . . .
3 Creating a GUI Programmatically3-12% Move the GUI to the center of the screen.movegui(f,'center')% Make the GUI visible.set(f,'Visibl
Initializing the GUI3-13 set([f,hsurf,hmesh,hcontour,htext,hpopup],... 'Units','normalized'); %Create a plot in the axes
3 Creating a GUI Programmatically3-14Programming the GUIYou use callbacks to program the GUI components. Callbacks are the functions that execute in r
Programming the GUI3-15 endThe next topic, “Programming the Push Buttons” on page 3-15, shows you how to write callbacks for the three push buttons.
3 Creating a GUI Programmatically3-16each component’s Callback property to specify the name of the callback with which it is associated. 1 To the uico
Running the Final GUI3-17Running the Final GUIYou have created the simple GUI. This topic shows you the final M-file and runs the GUI.• “The Final M-F
3 Creating a GUI Programmatically3-18 % Create the data to plot peaks_data = peaks(35); membrane_data = membrane; [x,y] = meshgrid(-8:.5:8);
Running the Final GUI3-19 end end % Push button callbacks. Each callback plots current_data in the % specified plot type. functi
3 Creating a GUI Programmatically3-202 In the pop-up menu, select Membrane, then click the Mesh button. The GUI displays a mesh plot of the MATLAB log
Creating GUIs with GUIDEThese sections describe how to create graphical user interfaces (GUIs) using GUIDE, the MATLAB® graphical user interface devel
viiCreating GUIs with GUIDE4What Is GUIDE?What Is GUIDE? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2Laying Out
4What Is GUIDE?What Is GUIDE? (p. 4-2) Introduces GUIDE, the MATLAB graphical user interface development environment.GUIDE Tools Summary (p. 4-3) Int
4 What Is GUIDE?4-2What Is GUIDE?GUIDE, the MATLAB Graphical User Interface development environment, provides a set of tools for creating graphical us
GUIDE Tools Summary4-3GUIDE Tools SummaryThe GUIDE tools are available from the Layout Editor shown in the figure below. The tools are called out in t
4 What Is GUIDE?4-4Tool Use This Tool To:Layout Editor Select components from the Component Palette, at the left side of the Layout Editor, and arrang
GUIDE Tools Summary4-5You can also set preferences that apply to all GUIs at creation, and options that are GUI-specific. See Chapter 5, “Preferences
4 What Is GUIDE?4-6
5Preferences and OptionsGUIDE Preferences (p. 5-2) MATLAB preferences for the GUIDE Layout Editor.GUI Options (p. 5-9) GUIDE options for individual G
5 Preferences and Options5-2GUIDE Preferences You can set preferences for the GUIDE Layout Editor by selecting Preferences from the MATLAB File menu.
GUIDE Preferences5-3Prompt to Save on ActivateWhen you activate a GUI by clicking the Run button , a dialog box informs you of the impending save and
viii ContentsSelecting a GUI Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5Accessing the Templates . . . . . . . . . . .
5 Preferences and Options5-4Prompt to Save on ExportWhen you select Export from the Layout Editor File menu, a dialog box informs you of the impending
GUIDE Preferences5-5All Other PreferencesThe GUIDE Layout Editor provides several other preferences. In the MATLAB Preferences dialog box, click GUIDE
5 Preferences and Options5-6The following topics describe the preferences in this dialog:• “Show Toolbar” on page 5-6• “Show Names in Component Palett
GUIDE Preferences5-7Show Names in Component PaletteDisplays both icons and names in the component palette, as shown below. When unchecked, the icons a
5 Preferences and Options5-8Show File Extension in Window TitleDisplays the filename with its file extension in the Layout Editor window title. If unc
GUI Options5-9GUI OptionsAfter opening a new GUI template in the Layout Editor, but before saving the GUI, you can configure various behaviors for the
5 Preferences and Options5-10• Non-resizable — Users cannot change the window size (default).•Proportional — MATLAB automatically rescales the compone
GUI Options5-11Generate FIG-File and M-FileSelect Generate FIG-file and M-file in the GUI Options dialog if you want GUIDE to create both the FIG-file
5 Preferences and Options5-12GUIDE also adds a callback whenever you edit a callback routine from the Layout Editor’s right-click context menu and whe
GUI Options5-13Note This option is available only if you first select the Generate FIG-file and M-File option.Generate FIG-File OnlyThe Generate FIG-
ix7Saving and Running the GUINaming a GUI and Its Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2The GUI Files . . . . . . . . .
5 Preferences and Options5-14MATLAB versions 5.3 and earlier. See the guide command for more information.• If you select Generate FIG-file only GUIDE
6Laying Out a GUIDesigning a GUI (p. 6-2) Things to think about when designing a GUI and references to other sources.Starting GUIDE (p. 6-4) Shows yo
6 Laying Out a GUI6-2Designing a GUIBefore creating the actual GUI, it is important to decide what it is you want your GUI to do and how you want it t
Designing a GUI6-3Many web sites and commercial publications such as the following provide guidelines for designing GUIs: • AskTog – Essays on good de
6 Laying Out a GUI6-4Starting GUIDEThere are many ways to start GUIDE. You can start GUIDE: • From the command line by typing guide. • From the Start
Selecting a GUI Template6-5Selecting a GUI TemplateGUIDE provides several templates that you can modify to create your own GUIs. The templates are ful
6 Laying Out a GUI6-62 Optionally, name your GUI now by selecting Save on startup as and typing the name in the field to the right. GUIDE saves the GU
Selecting a GUI Template6-7Select the blank GUI if the other templates are not suitable starting points for the GUI you are creating, or if you prefer
6 Laying Out a GUI6-8When you run the GUI by clicking the Run icon , the GUI appears as shown in the following figure.When a user enters values for t
Selecting a GUI Template6-9GUI with Axes and MenuThe GUI with axes and menu template is shown in the following figure. When you run the GUI by clickin
Comments to this Manuals