MATLAB ® The Language of Technical Computing Computation Visualization Programming Creating Graphical User Interfaces Version 1
How to Contact The MathWorks: www.mathworks.com comp.soft-sys.matlab Web Newsgroup info@mathworks.com Technical support Product enhancement suggestions Bug reports Documentation error reports Order status, license renewals, passcodes Sales, pricing, and general information 508-647-7000 Phone 508-647-7001 Fax The MathWorks, Inc. 3 Apple Hill Drive Natick, MA 01760-2098 Mail support@mathworks.com suggest@mathworks.com bugs@mathworks.com doc@mathworks.com service@mathworks.
Contents Getting Started with GUIDE 1 GUIDE – GUI Development Environment . . . . . . . . . . . . . . . 1-3 GUIDE Toolset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4 Understanding How to Create GUIs . . . . . . . . . . . . . . . . . . . . . 1-4 Getting Started Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5 Example – The GUI Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5 Example – Laying Out the GUI . . . . . . . . . . . . . .
MATLAB GUIs 2 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2 Creating GUIs with GUIDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3 GUI Development Environment . . . . . . . . . . . . . . . . . . . . . . . . . 2-3 Editing Version 5 GUIs with Version 6 GUIDE . . . . . . . . . . . 2-6 Selecting GUIDE Application Options . . . . . . . . . . . . . . . . . . . 2-8 Configuring the Application M-File . . . . . . . . . . . . . . . . . . . . . .
GUIDE Layout Tools 3 GUI Layout Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2 Laying Out GUIs – The Layout Editor . . . . . . . . . . . . . . . . . . . Placing an Object In the Layout Area . . . . . . . . . . . . . . . . . . . . . Activating the Figure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Saving the Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Displaying Your GUI . . . . . . . . . . . . . . . . . . . . .
Execution Paths in the Application M-File . . . . . . . . . . . . . . . . 4-4 Initializing the GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7 Managing GUI Data with the Handles Structure . . . . . . . . Passing Data in the Handles Structure . . . . . . . . . . . . . . . . . . Obtaining the Updated Handles Structure . . . . . . . . . . . . . . . If You Are Not Using a Handles Structure . . . . . . . . . . . . . . . . Application-Defined Data . . . . . . . . . . . . . . . . . .
Plot Push Button Callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7 Launching a Dialog to Confirm an Operation . . . . . . . . . . . . 5-9 Dialog Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9 View the Layout and Application M-File . . . . . . . . . . . . . . . . . 5-10 Implementing the GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10 The Close Button Callback . . . . . . . . . . . . . . . . . . . . . . . . . . . .
An Address Book Reader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Techniques Used in This Example . . . . . . . . . . . . . . . . . . . . . . Managing Global Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . View the Layout and Application M-File . . . . . . . . . . . . . . . . . Launching the GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Loading an Address Book Into the Reader . . . . . . . . . . . . . . . . The Contact Name Callback . . . . . . .
1 Getting Started with GUIDE GUIDE – GUI Development Environment . . . . . . . 1-3 GUIDE Toolset . . . . . . . . . . . . . . . . . . . 1-4 Understanding How to Create GUIs . . . . . . . . . . . 1-4 Getting Started Example . . . . . . . Example – The GUI Design . . . . . . . Example – Laying Out the GUI . . . . . . Creating the Layout . . . . . . . . . . Example – Programming the GUI . . . . . Example – Testing the GUI . . . . . . .
1 Getting Started with GUIDE This section illustrates the process of using GUIDE to create GUIs: • GUI Development Environment – overview of the layout tools provided by GUIDE. • Getting Started Example – an example illustrating how to use GUIDE. • User Interface Controls – descriptions of the components you use to create GUIs. For more in depth information about creating graphical users interfaces see MATLAB GUIs.
GUIDE – GUI Development Environment GUIDE – GUI Development Environment GUIDE, MATLAB’s Graphical User Interface development environment, provides a set of tools for laying out your GUI. The Layout Editor is the control panel for GUIDE. To start the Layout Editor, use the guide command. The following picture shows the Layout Editor with the Show names in component palette preference selected.
1 Getting Started with GUIDE GUIDE Toolset The following links provide more information on the full set of GUIDE development tools. • Layout Editor – add and arrange objects in the figure window. • Alignment Tool – align objects with respect to each other. • Property Inspector – inspect and set property values. • Object Browser – observe a hierarchical list of the Handle Graphics objects in the current MATLAB session.
Getting Started Example Getting Started Example This example shows how to create a GUI using GUIDE. It illustrates the process you should follow when creating your GUI. This process entails: • Design the GUI – often it is better to design the GUI on paper before beginning the implementation process. • Laying out the GUI figure – the GUI figure is the window that contains the user interface controls, such as push buttons and menus and can also contain axes for displaying graphs and images.
1 Getting Started with GUIDE File menu with Print and Close )LOH Surf Axes Mesh Push buttons to select plot type Contour Select Data peaks Popup for selecting data The popup menu contains three strings – “peaks”, “membrane”, and “sinc”, which enable the user to select the data to plot. The GUI program generates this data by executing one of three functions. Example – Laying Out the GUI This section illustrates how to layout GUI components (i.e.
Getting Started Example Note The following links execute MATLAB commands and are designed to work within the MATLAB Help browser. The first link adds a directory to your MATLAB path. Layout Editor with completed GUI layout MATLAB Editor with completed application M-file View an Animated Demo The following link displays an animated version of this example. Show GUIDE demonstration Creating the Layout Open the Layout Editor using the guide command.
1 Getting Started with GUIDE If you want to set the size of the GUI to an exact value, set the Position property using the Property Inspector (select Property Inspector from the View menu). Change the Units to inches to set the figure size, then change them back to characters before deploying the GUI.
Getting Started Example 2. Add the Components Select the components to add from the palette and drag them into the layout area. You can resize components from any corner handle while it is selected. Add three push buttons, a static text, a popup menu, and an axes. Arrange them as shown in the following picture.
1 Getting Started with GUIDE 3. Align the Objects To align components with respect to one another, select Align Objects from the Tools menu. The Alignment Tool sets the relative vertical and horizontal alignment of selected components. The following picture show the three push buttons selected (ctrl+click to multiple select) and ready to be aligned according to the settings: • 20 pixels spacing between push buttons in the vertical direction. • Left-aligned in the horizontal direction.
Getting Started Example 4. Set Properties for Each Component To set the properties of each component, select the Property Inspector from the View menu. Push Buttons and Static Text Set the String properties of the push buttons and static text to create the labels. For example, the following picture shows the Surf push button properties.
1 Getting Started with GUIDE Popup Menu Items Each item in the popup menu list needs to be on a separate line in the String property edit box: 1-12
Getting Started Example Tag and Callback Properties When you first add a component to the layout, its Callback property is set to the string .
1 Getting Started with GUIDE When you save or activate the GUI, GUIDE converts this string to one that calls the callback subfunction in the generated M-file. GUIDE uses the component’s Tag property to name its callback function. It is, therefore, useful to set Tag properties to descriptive names before you save or activate the GUI for the first time.
Getting Started Example This example sets the popup menu Tag to data_popup, resulting in the name data_popup_Callback for the popup menu’s callback function. Set the push button Tags to surf_pushbutton, mesh_pushbutton, and contour_pushbutton. The next section, Example – Programming the GUI, provides more information on the callback functions for this GUI.
1 Getting Started with GUIDE 5. Activate the GUI Activate the GUI by selecting Activate Figure from the Tools menu or use the activator button from the GUIDE toolbar. The following picture shows the GUI. See Activating the Figure for more detailed information on what figure activation does. The Application M-File Activating the GUI also opens the MATLAB editor with the M-file generated for the GUI. You must program the various components in your GUI in this M-file. The next section show how to do this.
Getting Started Example write the callbacks – the functions that execute when users activate a component in the GUI. The application M-file: • Initializes and launches the GUI. • Contains the callback functions for all components in the GUI. GUIDE generates this M-file with empty subfunctions for each component that has a callback associated with it – in this example, the three push buttons and the popup menu have callbacks.
1 Getting Started with GUIDE • Managing GUI Data Popup Menu Callback The popup menu enables users to select the data to plot. For simplicity, this example uses MATLAB functions to generate the data, but a more typical scenario would involve reading data from a file. This callback reads the popup menu Value property to determine what item is currently displayed and loads data into the handles structure accordingly.
Getting Started Example data_popup_Callback(handles.data_popup,[],handles) Push Button Callbacks Each of the push buttons creates a different type of plot using the data specified by the current selection in the popup menu. Their callbacks get data from the handles structure and then plot it. Surf push button callback: function varargout = surf_pushbutton_Callback(h,eventdata,handles,varargin) z = handles.
1 Getting Started with GUIDE Example – Adding the File Menu to the GUI The GUI has a File menu with two menu items: • Print – sends the plot to the user’s default printer. This item is grayed out if there is no plot currently displayed. • Close – closes the GUI window. To create the menu, display the Menu Editor by selecting the Menu Editor item in the Tool menu. 1. Add the File Menu Use the New Menu tool to add the top-level menu.
Getting Started Example 2. Set the Label and Tag Set the Label property to the word File. This is the name of the menu as it appears on the GUI menu bar. Set the Tag property to a descriptive name. GUIDE uses the Tag property to name the menu callback function (as well as the field in the handles structure that contains the menu handle). Initially, the Callback property is set to .
1 Getting Started with GUIDE 3. Add the Items Select File and click the New Menu Item tool. Each time you click New Menu Item, the editor adds a new submenu to the selected menu. 4. Set the Labels and Tags for the Menu Items Set the Label and Tag properties for each menu item. GUIDE generates a callback for each menu item as well. Save or activate the GUI to add the menu to the menu bar and to add the callbacks to the application M-file. The next section shows you how to program the menu.
Getting Started Example 5. Activate the GUI After creating the menus with the Menu Editor, you can activate the GUI from the Layout Editor. This causes GUIDE to generate the empty callback functions in the application M-file, which you can now program. Select sinc in the popup menu and click on the Mesh push button. The activated GUI looks like this when you pull down the File menu.
1 Getting Started with GUIDE Example – Programming the Menu Callbacks After adding the File menu to the layout (you cannot see the menu bar in the Layout Editor), edit the application M-file. It will contain empty callback functions for the File menu as well as the Print and Close items. File Menu Callback By default, when a user clicks on the File menu, MATLAB displays the menu items.
Getting Started Example else set(handles.print_submenu,'Enable','on') end The Print Item Callback The callback for the Print menu item uses the print command to print the current plot on the user’s default printer. The -f option specifies the GUI figure. Since the figure’s Tag property is set to figure1, the figure’s handle is contained in the figure1 field of the handles structure. function varargout = print_submenu_Callback(h, eventdata, handles, varargin) print -f handles.
1 Getting Started with GUIDE User Interface Controls The Layout Editor component palette contains the user interface controls that you can use in your GUI. These components are MATLAB uicontrol objects and are programmable via their Callback properties. This section provides information on these components. Push Buttons Sliders Toggle Buttons Frames Radio Buttons Listboxes Checkboxes Popup Menus Edit Text Axes Static Text Figures Push Buttons Push buttons generate an action when pressed (e.g.
User Interface Controls Toggle Buttons Toggle buttons generate an action and indicate a binary state (e.g., on or off). When you click on a toggle button, it appears depressed and remains depressed when you release the mouse button, at which point the callback executes. A subsequent mouse click returns the toggle button to the nondepressed state and again executes its callback. Programming the Callback The callback routine needs to query the toggle button to determine what state it is in.
1 Getting Started with GUIDE selected state at any given time). To activate a radio button, click the mouse button on the object. The display indicates the state of the button. Implementing Mutually Exclusive Behavior Radio buttons have two states – selected and not selected. You can query and set the state of a radio button through its Value property: • Value = Max, button is selected. • Value = Min, button is not selected.
User Interface Controls Checkboxes Check boxes generate an action when clicked and indicate their state as checked or not checked. Check boxes are useful when providing the user with a number of independent choices that set a mode (e.g., display a toolbar or generate callback function prototypes). The Value property indicates the state of the check box by taking on the value of the Max or Min property (1 and 0 respectively by default): • Value = Max, box is checked. • Value = Min, box is not checked.
1 Getting Started with GUIDE You can use the following code in the edit text callback. It gets the value of the String property and converts it to a double. It then checks if the converted value is NaN, indicating the user entered a non-numeric character (isnan) and displays an error dialog (errordlg).
User Interface Controls For example, these settings create a horizontal slider. Current Value, Range, and Step Size There are four properties that control the range and step size of the slider: • Value – contains the current value of the slider. • Max – defines the maximum slider value. • Min – defines the minimum slider value. • SliderStep – specifies the size of a slider step with respect to the range. The Value property contains the numeric value of the slider.
1 Getting Started with GUIDE Designing a Slider Suppose you want to create a slider with the following behavior: • Slider range = 5 to 8 • Arrow step size = 0.4 • Trough step size = 1 • Initial value = 6.5 From these values you need to determine and set the Max, Min, SliderStep, and Value properties. You can do this by adding the following code to the initialization section of the application M-file (after the creation of the handles structure). slider_step(1) = 0.
User Interface Controls Use the Bring to Front and Send to Back operations in the Layout menu for this purpose. List Boxes List boxes display a list of items and enable users to select one or more items. The String property contains the list of strings displayed in the list box. The first item in the list has an index of 1. The Value property contains the index into the list of strings that correspond to the selected item. If the user selects multiple items, then Value is a vector of indices.
1 Getting Started with GUIDE scrollbar). This means the callback is executed after the first click of a double-click on a single item or when the user is making multiple selections. In these situations, you need to add another component, such as a Done button (push button) and program its callback routine to query the list box Value property (and possibly the figure SelectionType property) instead of creating a callback for the list box.
User Interface Controls When not open, a popup menu displays the current choice, which is determined by the index contained in the Value property. The first item in the list has an index of 1. Popup menus are useful when you want to provide users with a number of mutually exclusive choices, but do not want to take up the amount of space that a series of radio buttons requires.
1 Getting Started with GUIDE • on – The control is operational • off – The control is disabled and its label (set by the string property) is grayed out. • inactive – The control is disabled, but its label is not grayed out. When a control is disabled, clicking on it with the left mouse button does not execute its callback routine.
User Interface Controls makes the axes whose Tag property is axes1 the current axes, and therefore the target for plotting commands. You can switch the current axes whenever you want to target a different axes. See GUI with Multiple Axes for and example that uses two axes. Figure Figures are the windows that contain the GUI you design with the Layout Editor. See the description of figure properties for information on what figure characteristics you can control.
1 Getting Started with GUIDE 1-38
2 MATLAB GUIs Introduction . . . . . . . . . . . . . . . . . . . . 2-2 Creating GUIs with GUIDE . . . . . . . . . . . . . 2-3 GUI Development Environment . . . . . . . . . . . . 2-3 Editing Version 5 GUIs with Version 6 GUIDE . . . . 2-6 Selecting GUIDE Application Options . . . . . . . . 2-8 Configuring the Application M-File . . . . . . . . . . . 2-8 Resize Behavior . . . . . . . Making Your GUI Nonresizable . . Allowing Proportional GUI Resizing User-Specified Resize Operation . . . . . . . . . . .
2 MATLAB GUIs Introduction A graphical user interface (GUI) is a user interface built with graphical objects, such as buttons, text fields, sliders, and menus. In general, these objects already have meanings to most computer users. For example, when you move a slider, a value changes; when you press an OK button, your settings are applied and the dialog box is dismissed. Of course, to leverage this built-in familiarity, you must be consistent in how you use the various GUI-building components.
Creating GUIs with GUIDE Creating GUIs with GUIDE MATLAB implements GUIs as figure windows containing various styles of uicontrol objects. You must program each object to perform the intended action when activated by the user of the GUI. In addition, you must be able to save and launch your GUI. All of these tasks are simplified by GUIDE, MATLAB’s graphical user interface development environment.
2 MATLAB GUIs GUI figure Resource file outing.fig Launch GUI outing.m Execute Callback Uicontrols Code file Features of the GUIDE-Generated Application M-File GUIDE simplifies the creation of GUI applications by automatically generating an M-file framework directly from your layout. You can then use this framework to code your application M-file.
Creating GUIs with GUIDE You can elect to have GUIDE generate only the FIG-file and write the application M-file yourself. Keep in mind that there are no uicontrol creation commands in the application M-file; the layout information is contained in the FIG-file generated by the Layout Editor. Beginning the Implementation Process To begin implementing your GUI, proceed to the following sections: • Getting Started with GUIDE – the basics of using GUIDE.
2 MATLAB GUIs Editing Version 5 GUIs with Version 6 GUIDE In MATLAB Version 5, GUIDE saved GUI layouts as MAT-file/M-file pairs. In MATLAB Version 6, GUIDE saves GUI layouts as FIG-files. GUIDE also generates an M-file to program the GUI callbacks, however, this M-file does not contain layout code. Use the following procedure to edit a Version 5 GUI with Version 6 GUIDE: 1 Display the Version 5 GUI. 2 Obtain the handle of the GUI figure. If the figure’s handle is hidden (i.e.
Editing Version 5 GUIs with Version 6 GUIDE application M-file generated by Version 6 GUIDE can provide a model of how to restructure your code. Note By default, GUIDE generates an application M-file having the same name as the FIG-file saved with the Layout Editor. When you activate a GUI from the Layout Editor, GUIDE attempts to execute this M-file to launch the GUI.
2 MATLAB GUIs Selecting GUIDE Application Options Issuing the guide command displays an empty Layout Editor with an untitled figure. Before adding components to the layout, you should configure the GUI using the GUIDE Application Options dialog. Access the dialog by selecting Application Options... from the Layout Editor Tools menu.
Selecting GUIDE Application Options • Generate .fig file and .
2 MATLAB GUIs Resize Behavior You can control whether users can resize the figure window containing your GUI and how MATLAB handles resizing. GUIDE provides three options: • Non-resizable – users cannot change the window size (default). • Proportional – MATLAB automatically rescales the components in the GUI in proportion to the new figure window size. • User-specified – program the GUI to behave in a certain way when users resize the figure window.
Resize Behavior This approach works well with simple GUI tools and dialog boxes that apply settings without closing. Users may want to resize these windows to better fit them on the screen, but the precise layout of the GUI is not critical to its function. Property Settings GUIDE sets the following properties to create proportional resizing GUIs: • Units properties of the axes and uicontrols should be set to normalized so the these components resize and reposition as the figure window changes size.
2 MATLAB GUIs Command-Line Accessibility When MATLAB creates a graph, the figure and axes are included in the list of children of their respective parents and their handles are available through commands such as findobj, set, and get. If you issue another plotting command, the output is directed to the current figure and axes. GUIs are also created in figure windows.
Command-Line Accessibility HandleVisibility – Callback Setting HandleVisibility to callback causes handles to be visible from within callback routines or functions invoked by callback routines, but not from within functions invoked from the command line.This provides a means to protect GUIs from command-line users, while allowing callback routines to have complete access to object handles. You should use this option if your GUI contains axes.
2 MATLAB GUIs Electing to Generate Only the FIG-File Select Generate .fig file only in the GUIDE Application Options dialog if you do not want GUIDE to generate an application M-file. When you save the GUI from the Layout Editor, GUIDE creates a FIG-file, which you can redisplay using the open or hgload command. When you select this option, you must set the Callback property of each component in your GUI to a string that MATLAB can evaluate and perform the desired action.
The Generated M-File The Generated M-File Select Generate .fig file and .m file in the GUIDE Application Options dialog if you want GUIDE to create both the FIG-file and the application M-file (this is the default).
2 MATLAB GUIs The arguments are listed in the following table. Callback Function Arguments h The handle of the object whose callback is executing. eventdata Empty, reserved for future use. handles A structure containing the handles of all components in the GUI whose fieldnames are defined by the object’s Tag property. Can also be used to pass data to other callback functions or the main program. varargin A variable-length list of arguments that you want to pass to the callback function.
The Generated M-File See Callback Function Syntax for more information on callback function arguments and Renaming Application Files and Tags for more information on how to change the names used by GUIDE. Adding Arguments to the Callback – varargin Callback subfunctions added by GUIDE require certain arguments, but have a variable-length argument list. Since the last argument is varargin, you can add whatever arguments you want to the subfunction.
2 MATLAB GUIs Defining Output Arguments – varargout GUIDE defines callbacks to return a variable number of arguments using varargout. See Passing Variable Numbers of Arguments for general information on using varargin and varargout. Application Allows Only One Instance to Run This option allows you to select between two behaviors for the GUI figure: • Allow MATLAB to display only one instance of the GUI at a time. • Allow MATLAB to display multiple instances of the GUI.
The Generated M-File If you select Use system color scheme for background (the default), GUIDE changes the figure background color to match the color of the GUI components. The following figures illustrate the results with (right) and without (left) system color matching. Code in the Application M-File GUIDE implements this feature by generating code in the application M-file that sets the figure background color to the default uicontrol background color, which is system dependent.
2 MATLAB GUIs Waiting for User Input The GUIDE application option, Function does not return until application window dismissed generates an application M-file that is designed to wait for user input. It does this by calling uiwait, which blocks further execution of the M-file. While execution waits, MATLAB processes the event queue.
Renaming Application Files and Tags Renaming Application Files and Tags It is often desirable to use descriptive names for component Tag properties and callback subfunction names. GUIDE assigns a value to the Tag property of every component you insert in your layout (e.g., pushbutton1) and then uses this string to name the callback subfunction (e.g., pushbutton1_Callback). It is generally a good practice to select the tags and filenames before activating or saving your GUI for the first time.
2 MATLAB GUIs If you change the Tag after GUIDE generates the callback subfunction, GUIDE does not generate a new subfunction. However, since the handles structure is created when you run the application M-file to launch the GUI, GUIDE uses the new Tag to name the field that contains the object’s handle. Problems Caused by Changing Tags Changing the Tag can cause program errors when you have referenced an objects handle. For example, the following statement, file_list = get(handles.
Renaming Application Files and Tags When you save or activate the figure, GUIDE changes to untitled('pushbutton6_Callback',gcbo,[],guidata(gcbo)) If you want to change the name of a callback, you must also change the string assigned to the Callback property. This picture shows what you must change the string to after you rename the callback subfunction to Closebutton_Callback.
2 MATLAB GUIs GUIDE generates similar strings for the other callback properties. Changing the Name of the M-File and FIG-File GUIDE gives the GUI FIG-file and its associated application M-file the same root name; only the extensions differ. When you execute the M-file to launch the GUI, the following statement uses the mfilename command to determine the name of the FIG-file from the name of the M-file.
3 GUIDE Layout Tools GUI Layout Tools . . . . . . . . . . . . . . . . . . 3-2 Laying Out GUIs – The Layout Editor . . . . . . . . 3-4 Aligning Components in the Layout Editor . . . . . . 3-10 Setting Component Properties – The Property Inspector 3-16 Viewing the Object Hierarchy – The Object Browser . . 3-18 Creating Menus – The Menu Editor . . . . . . . . . 3-19 Saving the GUI . . . . . . . . . . . . . . . . . . .
3 GUIDE Layout Tools GUI Layout Tools MATLAB includes a set of layout tools that simplify the process of creating graphical user interfaces (GUIs). These tools include: • Layout Editor – add and arrange objects in the figure window. • Alignment Tool – align objects with respect to each other. • Property Inspector – inspect and set property values. • Object Browser – observe a hierarchical list of the Handle Graphics objects in the current MATLAB session.
GUI Layout Tools Alignment Tool Menu Editor Property Inspector Object Browser Figure Activator Undo Redo Layout Area Component Palette Figure Resize Tab 3-3
3 GUIDE Layout Tools Laying Out GUIs – The Layout Editor The Layout Editor enables you to select GUI components from a palette and arrange them in a figure window. The component palette contains the GUI components (uicontrol objects) that are available for you to use in your user interface. The layout area becomes the figure window upon activation. Placing an Object In the Layout Area Select the type of component you want to place in your GUI by clicking on it in the component palette.
Laying Out GUIs – The Layout Editor Activating the Figure You can generate a functioning GUI by activating the figure you have designed with the Layout Editor. Activate the figure by selecting the Activate Figure item in the Tools menu or by clicking figure activator in the toolbar. When you activate a figure, the following occurs: • GUIDE first saves both the M-file and FIG-file.
3 GUIDE Layout Tools Saving the Layout Once you have created the GUI layout, you can save it as a FIG-file (a binary file that saves the contents of a figure) using the Save or Save As item from the File menu. GUIDE creates the application M-file automatically when you save or activate the figure. Displaying Your GUI You can display the GUI figure using the openfig, open, or hgload command. These commands load FIG-files into the MATLAB workspace.
Laying Out GUIs – The Layout Editor Layout Editor Context Menus When working in the Layout Editor, you can select an object with the left mouse button and then click the right button to display a context menu. In addition to containing items found on the Layout Editor window menu, this context menu enables you to add a subfunction to your application M-file for any of the additional object properties that define callback routines.
3 GUIDE Layout Tools GUI Component Context Menus The following picture shows the context menu associated with uicontrol objects. All the properties that define callback routines for this object are listed in the lower panel. Note that while axes do not have CallBack properties, you can program the ButtonDownFcn property callback to execute whenever the user clicks the mouse over the axes.
Laying Out GUIs – The Layout Editor 3-9
3 GUIDE Layout Tools Aligning Components in the Layout Editor You can select and drag any component or group of components within the layout area. In addition, the Layout Editor provides a number of features that facilitate more precise alignment of objects with respect to one another: • Alignment Tool – align and distribute groups of components. • Grid and Rulers – align components on a grid with optional snap to grid. • Guide Lines – vertical and horizontal snap-to guides at arbitrary locations.
Aligning Components in the Layout Editor • Align – align all selected components to a single reference line. • Distribute – space all selected components uniformly with respect to each other. Both types of alignment can be applied in the vertical and horizontal directions. Note that, in many cases, it is better to apply alignments independently to the vertical or to the horizontal using two separate steps. Align Options There are both vertical and horizontal align options.
3 GUIDE Layout Tools All of the align options (vertical top, center, bottom and horizontal left, center, right) place the selected components with respect to corresponding edge (or center) of this bounding box. Distribute Options Distributing components adds equal space between all components in the selected group.
Aligning Components in the Layout Editor Use the Grid and Rulers dialog (accessed by selecting Grid and Rulers from the Layout menu) to: • Control visibility of rulers, grid, and guide lines • Set the grid spacing • Enable or disable snap-to-grid Aligning Components to Guide Lines The Layout Editor has both vertical and horizontal snap-to guide lines. Components snap to the line when you move or resize them to within nine pixels of the line.
3 GUIDE Layout Tools Guide lines used for horizontal alignment Guide line used for vertical alignment Click on the top or left ruler and drag the guide to the desired position Front to Back Positioning The Layout Editor provides four operations that enable you to control the front to back positioning of objects that overlap: • Bring to Front – move the selected object(s) in front of nonselected objects (available from the right-click context menu or the Ctrl+F shortcut).
Aligning Components in the Layout Editor Access these operations from the Layout menu.
3 GUIDE Layout Tools Setting Component Properties – The Property Inspector The Property Inspector enables you to set the properties of the components in your layout. It provides a list of all settable properties and displays the current value. Each property in the list is associated with an editing device that is appropriate for the values accepted by the particular property.
Setting Component Properties – The Property Inspector • Right-clicking on a component and selecting Inspect Properties from the context menu.
3 GUIDE Layout Tools Viewing the Object Hierarchy – The Object Browser The Object Browser displays a hierarchical list of the objects in the figure. The following illustration shows the figure object and its child objects. The first uicontrol created was the frame. Next the radio buttons were added. Finally the axes was positioned next to the frame.
Creating Menus – The Menu Editor Creating Menus – The Menu Editor MATLAB enables you to create two kinds of menus: • Menubar objects – menus displayed on the figure menubar • Context menus – menus that pop up when users right-click on graphics objects You create both types of menus using the Menu Editor, which you can access from the Menu Editor item on the Tool menu and from the Layout Editor toolbar.
3 GUIDE Layout Tools Creating a Menu The first step is to use the New Menu tool to create a menu. Specifying Menu Properties When you click on the menu, text fields appear that allow you to set the Label, Tag, Separator, and Checked menu properties as well as specifying the Callback string.
Creating Menus – The Menu Editor Adding Items to the Menu Use the New Menu Item tool to define the menu items that are displayed under the top-level menu. New Menu Item adds a submenu to the selected item. For example, if you add a Print item to the File menu in the illustration above, select File before clicking on New Menu Item. Fill in the Label and Tag text fields for the new submenu.
3 GUIDE Layout Tools Create additional levels in the same way. For example, the following picture show an Edit menu having a Copy submenu, which itself has two submenus. Laying Out Three Menus The following Menu Editor illustration shows three menus defined for the figure menubar.
Creating Menus – The Menu Editor When you activate the figure, the menus appear in the menubar.
3 GUIDE Layout Tools Menu Callbacks By default, the Callback text field in the Menu Editor is set to the string . This causes GUIDE to add the empty callback subfunction to the application M-file when you save or activate the GUI. If you change this string. GUIDE does not add a subfunction for that menu item.
Creating Menus – The Menu Editor For example, using the Select All menu item from the previous example gives the following callback string: MyGui('menu_edit_selectall_Callback',gcbo,[],guidata(gcbo)) where: • MyGui – is the name of the application M-file that launches the figure containing the menus. • menu_edit_selectall_Callback – is the name of the subfunction callback for the Select All menu item (derived from the Tag specified in the Menu Editor). • gcbo – is the handle of the Select All uimenu item.
3 GUIDE Layout Tools Creating the Parent Menu All items in a context menu are children of a menu that is not displayed on the figure menubar. To define the parent menu, select New Context Menu from the Menu Editor’s toolbar. Note You must select the Menu Editor’s Context Menus tab before you begin to define a context menu. Select the menu and specify the Tag to identify the context menu (axes_context_menu in this example).
Creating Menus – The Menu Editor When you select the menu item, the Menu Editor displays text fields for you to enter the menu Label and Tag properties. Associating the Context Menu with an Object Select the object in the Layout Editor for which you are defining the context menu. Use the Property Inspector to set this object’s UIContextMenu property to the desired context menu.
3 GUIDE Layout Tools Add a callback routine subfunction to the application M-file for each item in the context menu. This callback executes when users select the particular context menu item. See The Menu Callback for information on defining the syntax.
Saving the GUI Saving the GUI The FIG-file that you create with the Layout Editor enables MATLAB to reconstruct your GUI when it is deployed. Generally, a functional GUI consists of two components: • A FIG-file – containing a description of the GUI • An M-file – containing the program that controls the GUI once it is deployed FIG-Files FIG-files (filename.fig) are binary files created as a result of saving a figure with the hgsave command or using Save from the Layout Editor’s File menu.
3 GUIDE Layout Tools Opening FIG-Files You can use the open, openfig, and hgload commands to open a file having a .fig extension. The application M-file uses openfig to display the GUI.
4 Programming GUIs GUI Programming Topics . . . . . . . . . . . . . . 4-2 Understanding the Application M-File . . . . . . . . 4-3 Execution Paths in the Application M-File . . . . . . . . 4-4 Initializing the GUI . . . . . . . . . . . . . . . . . 4-7 Managing GUI Data with the Handles Structure Passing Data in the Handles Structure . . . . . . . Obtaining the Updated Handles Structure . . . . . If You Are Not Using a Handles Structure . . . . . Application-Defined Data . . . . . . . . . . . . . . . . . .
4 Programming GUIs GUI Programming Topics Graphical user interfaces (GUIs) contain various user-interface components that enable software to communicate with an end user. One of the tasks of the GUI implementer is to control how the GUI responds to user actions. This section describes ways to approach the programming of the GUI. • Understanding the Application M-File – The application M-file programs the GUI.
Understanding the Application M-File Understanding the Application M-File MATLAB generates the application M-file to provide a framework for the program that controls the GUI. This framework fosters a programming style that is efficient and robust. All code, including the callbacks, is contained in the single application M-file. The following code is the initialization section of the application M-file. This code is generated by GUIDE.
4 Programming GUIs • Execution Paths in the Application M-File • Initializing the GUI • Managing GUI Data with the Handles Structure Execution Paths in the Application M-File The application M-file follows different execution paths depending on what arguments you use. For example: • Calling the M-file with no arguments launches the GUI (if you assign an output argument, the M-file returns the handle of the GUI figure).
Understanding the Application M-File catch disp(lasterr); end end Any output arguments returned by your callback subfunction are then returned though the main function via the first feval statement: if (nargout) % If there are output arguments [varargout{1:nargout}] = feval(varargin{:}); In addition, any input arguments you have added to the Callback property string are included in the evaluated statement.
4 Programming GUIs Application M-File Execution Path Call application M-file Single or Multiple Instance Check input arguments If no arguments launch GUI Figure exists and is reused Yes Raise GUI figure No Arguments > 0 and first argument is string Open figure GUI Initialization Use system background color Execute Callback Build handles struct from Tag properties feval the variable argument list • First argument is subfunction name • Pass remaining arguments to subfunction Wait for user inpu
Understanding the Application M-File Initializing the GUI The application M-file automatically includes some useful techniques for managing the GUI. These technique include: • Open the FIG-file. • Single/multiple instance control. • On screen placement of the GUI figure regardless of target computer screen size and resolution. • Structure containing GUI component handles automatically created.
4 Programming GUIs Positioning the GUI Onscreen The application M-file uses the movegui command to ensure the GUI figure is visible on the screen of the target computer, regardless of the screen size and resolution. If the specified figure position would result in the GUI being placed off screen, movegui moves the figure to the nearest on-screen location with respect to the specified position.
Understanding the Application M-File The handles structure is one of the arguments passed to each callback. You can also use this same structure to save data and pass it between subfunctions. See Managing GUI Data for a discussion of how to use the handles structure for data.
4 Programming GUIs Managing GUI Data with the Handles Structure GUIDE provides a mechanism for storing and retrieving global data using the same structure that contains the GUI component handles. The handles structure, which containing the handles of all the components in the GUI, is passed to each callback in the application M-file. Therefore, this structure is useful for saving any global data. The following example illustrates this technique.
Managing GUI Data with the Handles Structure Defining the Data Fields During Initialization The following excerpt from the GUI setup code show two additional fields defined in the handles structure – errorString and numberOfErrors: • guihandles creates the structure and adds the handles of the slider and edit text using the Tag property to name the fields (edit1 and slider1). • guidata saves the handles structure. This function can return the handles structure as well.
4 Programming GUIs else % Increment the error count, and display it handles.numberOfErrors = handles.numberOfErrors+1; set(handles.edit1,'String',... [handles.errorString,num2str(handles.numberOfErrors)]); guidata(gcbo,handles); % store the changes end Saving the Handles Structure You must use guidata to save the handles structure whenever you change values in that structure. The statement, guidata(gcbo,handles); saves the current handles structure for the GUI figure.
Managing GUI Data with the Handles Structure • Retrieving the structure within the subfunction when it is required. Using the guidata Function without the Handles Structure The guidata function provides a convenient interface to the figure’s application data.
4 Programming GUIs Application-Defined Data Application-defined data provides a way for applications to save and retrieve data stored with the GUI. This technique enables you to create what is essentially a user-defined property for an object. You can use this property to store data. The application M-file uses application data to store the handles structure. When using the GUIDE-generated application M-file, it is simpler to use guidata than to access application data directly.
Designing for Cross-Platform Compatibility Designing for Cross-Platform Compatibility You can use specific property settings to create a GUI that behaves more consistently when run on different platforms: • Use the default font (uicontrol FontName property). • Use the default background color (uicontrol BackgroundColor property). • Use figure character units (figure Units property). Using the Default System Font By default, uicontrols use the default font for the platform on which they are running.
4 Programming GUIs Specifying a Fixed-Width Font If you want to use a fixed-width font for a uicontrol, set its FontName property to the string fixedwidth. This special identifier ensures that your GUI 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.
Designing for Cross-Platform Compatibility on UNIX). When your GUI is deployed on a different platform, it uses that computer’s standard color. This provides a consistent look with respect to your GUI and other application GUIs. If you change the BackgroundColor to another value, MATLAB always uses the specified color. Cross-Platform Compatible Figure Units Cross-platform compatible GUIs should look correct on computers having different screen sizes and resolutions.
4 Programming GUIs Types of Callbacks The primary mechanism for implementing a GUI is programming the callback of the uicontrol objects used to build the interface. However, in addition to the uicontrol Callback property, there are other properties that enable you to define callbacks.
Types of Callbacks • WindowButtonUpFcn – MATLAB executes the specified callback when users release the mouse button, after having pressed the mouse button within the figure. Which Callback Executes Clicking on an enabled uicontrol prevents any ButtonDownFcn and WindowButtonDownFcn callbacks from executing.
4 Programming GUIs Interrupting Executing Callbacks By default, MATLAB allows an executing callback to be interrupted by subsequently invoked callbacks. For example, suppose you have created a dialog box that displays a progress indicator while loading data. This dialog could have a “Cancel” button that stops the loading operation. The “Cancel” button’s callback routine would interrupt the currently executing callback routine.
Interrupting Executing Callbacks • drawnow • figure • getframe • pause • waitfor When MATLAB encounters one of these commands in a callback, it suspends execution and processes the events in the event queue. The way MATLAB handles an event depends on the event type and the setting of the callback object’s Interruptible property: • Events that would cause another callback to execute (e.g.
4 Programming GUIs 2 If the event at the top of the queue calls for a figure window redraw, MATLAB performs the redraw and proceeds to the next event in the queue. 3 If the event at the top of the queue would cause a callback to execute, MATLAB determines whether the object whose callback is suspended is interruptible. 4 If the callback is interruptible, MATLAB executes the callback associated with the interrupting event.
Controlling GUI Figure Window Behavior Controlling GUI Figure Window Behavior When designing a GUI you need to consider how you want the figure window to behave. The appropriate behavior for a particular GUI figure depends on intended use. Consider the following examples: • A GUI that implements tools for annotating graphs is usually designed to be available while the user performs other MATLAB tasks.
4 Programming GUIs Making a GUI Figure Modal Set the GUI figure’s WindowStyle property to modal to make the window modal. You can use the Property Inspector to change this property or add a statement in the initialization section of the application M-file, using the handle returned by openfig with the set command. set(fig,'WindowStyle','modal') Dismissing a Modal Figure A GUI using a modal figure must take one of the following actions in a callback routine to release control: • Delete the figure.
5 Application Examples Examples of Application Techniques . . . . . . . . . 5-2 GUI with Multiple Axes . . . . . . . . . . . . . . . 5-3 Launching a Dialog to Confirm an Operation . . . . . 5-9 List Box Directory Reader . . . . . . . . . . . . . 5-18 Accessing Workspace Variables from a List Box . . . . 5-24 A GUI to Set Simulink Model Parameters . . . . . . . 5-28 An Address Book Reader . . . . . . . . . . . . . .
5 Application Examples Examples of Application Techniques This section contains a series of examples that illustrate techniques that are useful for implemented GUIs. Each example provides a link to the actual GUI in the GUIDE Layout Editor and a link to the application M-file displayed in the MATLAB editor. Note It is important that you use the links in each section to display the layouts and M-files when reading these examples. To do this, you must be running MATLAB and using the MATLAB Help browser.
GUI with Multiple Axes GUI with Multiple Axes This example creates a GUI that contains two axes for plotting data. For simplicity, this example obtains data by evaluating an expression using parameters entered by the user. Techniques Used in the Example GUI-building techniques illustrated in this example include: • Controlling which axes is the target for plotting commands. • Using edit text controls to read numeric input and MATLAB expressions.
5 Application Examples View the Layout and Application M-File Use the following links to display the GUIDE Layout Editor and the MATLAB Editor with a completed version of this example. This enables you to see the values of all component properties and to understand how the components are assembled to create the GUI. You can also see a complete listing of the code that is discussed in the following sections.
GUI with Multiple Axes Identifying the Axes Since there are two axes in this GUI, you must be able to specify which one you want to target when you issue the plotting commands. To do this, use the handles structure, which contains the handles of all components in the GUI. The field name in the handles structure that contains the handle of any given component is derived from the component’s Tag property.
5 Application Examples For example, the Tag of the axes used to display the FFT is set to frequency_axes. Therefore, within a callback, you access its handle with handles.frequency_axes Likewise, the Tag of the time axes is set to time_axes. See Creating and Storing the Handles Structure for more information on the handles structure. See “Plot Push Button Callback” for the details of how to use the handle to specify the target axes.
GUI with Multiple Axes Callback Accessibility of Object Handles. When GUIs include axes, handles should be visible from within callbacks. This enables you to use plotting commands like you would on the command line. Note that Callback is the default setting for command-line accessibility. Plot Push Button Callback This GUI uses only the Plot button callback; the edit text callbacks are not needed and have been deleted from the application M-file.
5 Application Examples • Making the appropriate axes current using the axes command and the handle of the axes. For example, axes(handles.frequency_axes) • Issuing the plot command. • Setting any properties that are automatically reset by the plot command. The last step is necessary because many plotting commands (including plot) clear the axes before creating the graph.
Launching a Dialog to Confirm an Operation Launching a Dialog to Confirm an Operation This example illustrates how to display a dialog when users attempt to close a GUI. The purpose of the dialog is to force the user to confirm that they really want to proceed with the close operation. The following picture illustrates the dialog positioned over the GUI application, awaiting the user’s response.
5 Application Examples • Handle the case where the user closes the dialog from the window manager close box without responding. The following sections discuss the implementation of this dialog. View the Layout and Application M-File Use the following links to display the GUIDE Layout Editor and the MATLAB Editor with a completed version of this example. This enables you to see the values of all component properties and to understand how the components are assembled to create the GUI.
Launching a Dialog to Confirm an Operation Making the Dialog Modal To make the dialog modal, select the figure in the Layout Editor and right-click to display the context menu. Select Property Inspector from the context menu. Use the Property Inspector to set the figure’s WindowStyle property to modal.
5 Application Examples 3 Once the user makes a choice, the confirmation dialog callbacks resume execution and return a value to the Close button callback. 4 Close button callback resumes execution and takes appropriate action based on user response to the confirmation dialog. The Close Button Callback The Close button callback performs the following tasks: • Determines where to locate of the confirmation dialog based on the current size and location of the GUI application figure.
Launching a Dialog to Confirm an Operation • One numeric argument – launch the dialog and place it at the location specified in a two-element vector. • Four arguments – call the Yes or No button callback with the usual arguments (h,eventdata,handles,varargin). With each calling syntax, the M-file returns a string output argument indicating the user response.
5 Application Examples Specify the Location of the Dialog The dialog M-file accepts an input argument that specifies where to display the dialog. This enables the Close button callback to locate the dialog with respect to the main application window. The argument is a two-element vector containing the left and bottom offsets from the right and lower edge of the screen, in character units. The Close button callback determines these values.
Launching a Dialog to Confirm an Operation • The No button callback executes uiresume after setting handles.answer to 'no'. uiwait(fig); if ~ishandle(fig) answer = 'cancel'; else handles = guidata(fig); answer = handles.answer; delete(fig); end Executing a Callback This is the feval switchyard that enables modaldlg to execute the callback subfunctions. It relies on the fact that when modaldlg is called to execute a callback, the first argument is a string (the name of the callback).
5 Application Examples uiresume(handles.figure1); function varargout = yesButton_Callback(h, eventdata, handles, varargin) handles.answer = 'yes'; guidata(h,handles); uiresume(handles.figure1); Protecting the GUI with a Close Request Function Whenever a user closes a figure, MATLAB first executes the figure’s close request function, as defined by the CloseRequestFcn figure property. The default close request function simply deletes the figure.
Launching a Dialog to Confirm an Operation Select Edit CloseRequestFcn from the context menu. GUIDE automatically places a new subfunction in the application M-file for the GUI and changes the figure’s CloseRequesFcn property to execute this subfunction as the close request function. The Redefined Close Request Function The GUIs close request function simply calls the Close button’s callback.
5 Application Examples List Box Directory Reader This example uses a list box to display the files in a directory. When the user double clicks on a list item, one of the following happens: • If the item is a file, the GUI opens the file appropriately for the file type. • If the item is a directory, the GUI reads the contents of that directory into the list box. • If the item is a single dot (.), the GUI updates the display of the current directory. • If the item is two dots (..
List Box Directory Reader Note The following links execute MATLAB commands and are designed to work within the MATLAB Help browser. The first link adds a directory to your MATLAB path. Click here to display this GUI in the Layout Editor. Click here to display the application M-file in the editor. Implementing the GUI The following sections describe the implementation. • Specifying the Directory to List – shows how to pass a directory path as input argument when the GUI is launched.
5 Application Examples The following code listing show the entire initialization section of the application M-file. The statements in bold are the additions made to the generated code. function varargout = lbox2(varargin) if nargin <= 1 % LAUNCH GUI if nargin == 0 initial_dir = pwd; elseif nargin == 1 & exist(varargin{1},'dir') initial_dir = varargin{1}; else errordlg('Input argument must be a valid directory',...
List Box Directory Reader Loading the List Box This example creates a subfunction to load items into the list box. This subfunction accepts the path to a directory and the handles structure as input arguments. It performs these steps: • Change to the specified directory so the GUI can navigate up and down the tree as required. • Use the dir command to get a list of files in the specified directory and to determine which name is a directory and which is a file.
5 Application Examples The List Box Callback The list box callback handles only one case: a double click on an item. Double clicking is the standard way to open a file from a list box. If the selected item is a file, it is passed to the open command; if it is a directory, the GUI changes to that directory and lists its contents. Defining How to Open File Types The callback makes use of the fact that the open command can handle a number of different file types.
List Box Directory Reader The open statement is called within a try/catch block to capture errors in an error dialog (errordlg), instead of returning to the command line. function varargout = listbox1_Callback(h,eventdata,handles,varargin) if strcmp(get(handles.figure1,'SelectionType'),'open') % If double click index_selected = get(handles.listbox1,'Value'); file_list = get(handles.listbox1,'String'); filename = file_list{index_selected}; % Item selected in list box if handles.is_dir(handles.
5 Application Examples Accessing Workspace Variables from a List Box This GUI uses a list box to display workspace variables, which the user can then plot. Techniques Used in This Example This example demonstrates how to: • Populate the list box with the variable names that exist in the base workspace. • Display the list box with no items initially selected. • Enable multiple item selection in the list box. • Update the list items when the user press a button.
Accessing Workspace Variables from a List Box • Delete the string assigned to the list box Callback property. View the Layout and Application M-File Use the following links to display the GUIDE Layout Editor and the MATLAB Editor with a completed version of this example. This enables you to see the values of all component properties and to understand how the components are assembled to create the GUI. You can also see a complete listing of the code that is discussed in the following sections.
5 Application Examples Reading the Selections from the List Box This GUI requires the user to select two variables from the workspace and then choose one of three plot commands to create the graph – plot, semilogx, semilogy. Enabling Multiple Selection To enable multiple selection in a list box, you must set the Min and Max properties so that Max – Min > 1. This requires you to change the default Min and Max values of 0 and 1 to meet these conditions.
Accessing Workspace Variables from a List Box var1 = list_entries{index_selected(1)}; var2 = list_entries{index_selected(2)}; end Callbacks for the Plotting Buttons The callbacks for the plotting buttons call get_var_names to get the names of the variables to plot and then call evalin to execute the plot commands in the base workspace.
5 Application Examples A GUI to Set Simulink Model Parameters This example illustrates how to create a GUI that sets the parameters of a Simulink model. In addition, the GUI can run the simulation and plot the results. The following picture shows the GUI after running three simulations with different values for controller gains. Techniques Used in This Example This example illustrates a number of GUI building techniques: • Opening and setting parameters on a Simulink model from a GUI.
A GUI to Set Simulink Model Parameters assembled to create the GUI. You can also see a complete listing of the code that is discussed in the following sections. Note The following links execute MATLAB commands and are designed to work within the MATLAB Help browser. The first link adds a directory to your MATLAB path. Click here to display this GUI in the Layout Editor. Click here to display the application M-file in the editor.
5 Application Examples Plotting the Results You can generate a plot of one or more simulation results by selecting the row of results (Run1, Run2, etc.) in the Results list that you want to plot and clicking the Plot button. If you select multiple rows, the graph contains a plot of each result. The graph is displayed in a figure, which is cleared each time you click the Plot button. The figure’s handle is hidden so that only the GUI can display graphs in this window.
A GUI to Set Simulink Model Parameters • Change the size of the controller Gain block so it can display the gain value (set_param). • Bring the GUI forward so it is displayed on top of the Simulink diagrams (figure). • Set the block parameters to match the current settings in the GUI. Here is the code for the model_open subfunction.
5 Application Examples • Sets the value of the Current value edit text component to match the slider. • Sets the appropriate block parameter to the new value (set_param). Here is the callback for the Proportional (Kf) slider. function varargout = KfValueSlider_Callback(h,eventdata,handles,varargin) % Ensure model is open model_open(handles) % Get the new value for the Kf Gain from the slider NewVal = get(h,'Value'); % Set the value of the KfCurrentValue to the new value set by slider set(handles.
A GUI to Set Simulink Model Parameters model_open(handles) % Get the new value for the Kf Gain NewStrVal = get(h,'String'); NewVal = str2double(NewStrVal); % Check that the entered value falls within the allowable range if isempty(NewVal) | (NewVal< -5) | (NewVal>0), % Revert to last value, as indicated by KfValueSlider OldVal = get(handles.KfValueSlider,'Value'); set(h,'String',OldVal) else, % Use new Kf value % Set the value of the KfValueSlider to the new value set(handles.
5 Application Examples ResultsData = handles.ResultsData; % Determine the maximum run number currently used. maxNum = ResultsData(length(ResultsData)).RunNumber; ResultNum = maxNum+1; else % Set up the results data structure ResultsData = struct('RunName',[],'RunNumber',[],... 'KiValue',[],'KfValue',[],'timeVector',[],'outputVector',[]); ResultNum = 1; end if isequal(ResultNum,1), % Enable the Plot and Remove buttons set([handles.RemoveButton,handles.
A GUI to Set Simulink Model Parameters structure. When a user clicks on the Remove button, the callback executes the following steps: • Determines which list box items are selected when a user clicks on the Remove button and removes these items from the list box String property by setting each item to the empty matrix []. • Removes the deleted data from the handles structure.
5 Application Examples • Collects the data for each run selected in the Results list, including two variables (time vector and output vector) and a color for each result run to plot. • Generates a string for the legend from the stored data. • Creates the figure and axes for plotting and saves the handles for use by the Close button callback. • Plots the data, adds a legend, and makes the figure visible.
A GUI to Set Simulink Model Parameters PlotData{ctVal*3} = plotColor{numColor}; legendStr{ctVal} = [handles.ResultsData(currentVal(ctVal)).RunName,... '; Kf=', ... num2str(handles.ResultsData(currentVal(ctVal)).KfValue),... '; Ki=', ... num2str(handles.ResultsData(currentVal(ctVal)).KiValue)]; end % If necessary, create the plot figure and store in handles structure if ~isfield(handles,'PlotFigure') | ~ishandle(handles.PlotFigure), handles.PlotFigure = figure('Name','F14 Simulation Output',...
5 Application Examples Closing the GUI The GUI Close button callback closes the plot figure, if one exists and then closes the GUI. The handle of the plot figure and the GUI figure are available from the handles structure. The callback executes two steps: • Checks to see if there is a PlotFigure field in the handles structure and if it contains a valid figure handle (the user could have closed the figure manually). • Closes the GUI figure This is the Close button callback.
A GUI to Set Simulink Model Parameters See the description of list boxes for more information on how to trigger the list box callback.
5 Application Examples An Address Book Reader This example shows how to implement a GUI that displays names and phone numbers, which it reads from a MAT-file. Techniques Used in This Example This example demonstrates the following GUI programming techniques: • Uses open and save dialogs to provide a means for users to locate and open the address book MAT-files and to save revised or new address book MAT-files. • Defines callbacks written for GUI menus.
An Address Book Reader • The names and phone numbers stored in the MAT-file. • An index pointer that indicates the current name and phone number, which must be updated as the user pages through the address book. • The figure position and size. • The handles of all GUI components. The descriptions of the subfunctions that follow illustrate how to save and retrieve information from the handles structure. See Managing GUI Data with the Handles Structure for background information on this structure.
5 Application Examples • Application M-file options selected: Generate callback function prototypes Application allows only one instance to run Launching the GUI You can call the application M-file with no arguments, in which case the GUI uses the default address book MAT-file, or you can specify a MAT-file as an argument. Specifying a MAT-file as an input argument requires modification to the default GUI initialization section of the application M-file. The following code shows these changes in bold.
An Address Book Reader catch disp(lasterr); end end Loading an Address Book Into the Reader There are two ways in which an address book (i.e., a MAT-file) is loaded into the GUI: • When launching the GUI, you can specify a MAT-file as an argument. If you do not specify an argument, the GUI loads the default address book (addrbook.mat). • The user can select Open under the File menu to browse for other MAT-files.
5 Application Examples % If called without any file then set file to the default file name. % Otherwise if the file exists then load it. if isempty(file) file = 'addrbook.mat'; handles.LastFile = file; guidata(handles.
An Address Book Reader (uigetfile) that enables the user to browser for files. The dialog displays only MAT-files, but users can change the filter to display all files. The dialog returns both the filename and the path to the file, which is then passed to fullfile to ensure the path is properly constructed for any platform. Check_And_Load validates and load the new address book.
5 Application Examples Storing and Retrieving Data This callback makes use of the handles structure to access the contents of the address book and to maintain an index pointer (handles.Index) that enables the callback to determine what name was displayed before it was changed by the user. The index pointer indicates what name is currently displayed. The address book and index pointer fields are added by the Check_And_Load function when the GUI is launched.
An Address Book Reader 'Yes','Cancel','Yes'); switch Answer case 'Yes' Addresses(end+1).Name = Current_Name; % Grow array by 1 Addresses(end).Phone = Current_Phone; index = length(Addresses); handles.Addresses = Addresses; handles.Index = index; guidata(h,handles) return case 'Cancel' % Revert back to the original number set(handles.Contact_Name,'String',Addresses(handles.Index).Name) set(handles.Contact_Phone,'String',Addresses(handles.Index).
5 Application Examples Addresses = handles.Addresses; Answer=questdlg('Do you want to change the phone number?', ... 'Change Phone Number', ... 'Yes','Cancel','Yes'); switch Answer case 'Yes' % If no name match was found create a new contact Addresses(handles.Index).Phone = Current_Phone; handles.Addresses = Addresses; guidata(h,handles) return case 'Cancel' % Revert back to the original number set(handles.Contact_Phone,'String',Addresses(handles.Index).
An Address Book Reader button Callback string includes 'Next' as the last argument. The value of str is used in case statements to implement each button’s functionality (see the code listing below). Paging Forward or Backward Prev_Next_Callback gets the current index pointer and the addresses from the handles structure and, depending on which button the user presses, the index pointer is decremented or incremented and the corresponding address and phone number are displayed.
5 Application Examples set(handles.Contact_Name,'string',Current_Name) set(handles.Contact_Phone,'string',Current_Phone) % Update the index pointer to reflect the new index handles.Index = i; guidata(h,handles) Saving Changes to the Address Book from the Menu When you make changes to an address book, you need to save the current MAT-file, or save it as a new MAT-file. The File submenus Save and Save As enable you to do this. These menus, created with the Menu Editor, use the same callback, Save_Callback.
An Address Book Reader Save_Callback Code Listing function varargout = Save_Callback(h, eventdata, handles, varargin) % Get the Tag of the menu selected Tag = get(h,'Tag'); % Get the address array Addresses = handles.Addresses; % Based on the item selected, take the appropriate action switch Tag case 'Save' % Save to the default addrbook file File = handles.LastFile; save(File,'Addresses') case 'Save_As' % Allow the user to select the file name to save to [filename, pathname] = uiputfile( ... {'*.mat';'*.
5 Application Examples The Address Book Resize Function The address book defines it’s own resize function. To use this resize function, you must set the Application Options dialog Resize behavior to “User-specified”, which in turn sets the figure’s ResizeFcn property to: address_book('ResizeFcn',gcbo,[],guidata(gcbo)) Whenever the user resizes the figure, MATLAB calls the ResizeFcn subfunction in the address book application M-file (address_book.
An Address Book Reader original position of the GUI on screen. Therefore, the resize function applies a compensation to the vertical position (second element in the figure Position vector) as follows: vertical position when mouse released + height when mouse released – original height When the figure is resized from the bottom, it stays in the same position. When resized from the top, the figure moves to the location where the mouse button is released.
5 Application Examples % Adjust the size of the Contact Name text box % Set the units of the Contact Name field to 'Normalized' set(handles.Contact_Name,'units','normalized') % Get its Position C_N_pos = get(handles.Contact_Name,'Position'); % Reset it so that it's width remains normalized relative to figure set(handles.Contact_Name,'Position',... [C_N_pos(1) C_N_pos(2) 0.789 C_N_pos(4)]) % Return the units to ’Characters’ set(handles.
Index A activate figure 3-5 aligning GUI components 3-10 Alignment Tool, for GUIs 3-10 application data 4-14 application M-file 2-3, 4-3 application options 2-8 axes multiple in GUI 5-3 axes, plotting when hidden 5-36 C callback 2-3 arguments 2-16 callback syntax 2-15 callbacks adding arguments 2-17 interrupting 4-20 types 4-18 check boxes 1-29 checkboxes 1-29 close request function in GUI 5-16 color of GUI background 2-18 command-line accessibility of GUIs 2-12 context menus 3-25 controls, for GUIs 1-26
Index waiting for user input 2-20 guide 3-2 GUIs, saving 3-29 H handles structure 4-10 handles structure in GUIs 4-8 help button for GUIs 5-37 hidden figure, accessing 5-36 L Layout Editor 3-4 controls 1-3 Layout Tools, GUI 3-2 list box example 5-18 list boxes 1-33 M Menu Editor 3-19 menus adding to GUI 1-20 context 3-25 popup 1-34 M-file generated by GUIDE 2-15 modal GUIs 4-23 P pop-up menus 1-34 popup menus 1-34 Property Inspector 3-16 push button 1-26 push buttons 1-26 R radio buttons 1-27 renaming