MATLAB ® The Language of Technical Computing Creating Graphical User Interfaces Version 7
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 What Is GUIDE? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 Starting GUIDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3 The Layout Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4 GUIDE Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6 Running a GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Setting Properties for GUI Components . . . . . . . . . . . . . . . . Name Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Title Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . String Property for Push Buttons and Static Text . . . . . . . . . . String Property for Pop-up Menus . . . . . . . . . . . . . . . . . . . . . . Callback Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Tag Property . . . .
Layout Editor Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-22 Layout Editor Context Menus . . . . . . . . . . . . . . . . . . . . . . . . . . 3-23 Selecting GUI Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring the GUI M-File . . . . . . . . . . . . . . . . . . . . . . . . . . . Resize Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Command-Line Accessibility . . . . . . . . . . . . . . . . . . . . . . . . . . .
Programming GUIs 4 Understanding the GUI M-File . . . . . . . . . . . . . . . . . . . . . . . . . Sharing Data with the Handles Structure . . . . . . . . . . . . . . . . . Functions and Callbacks in the M-File . . . . . . . . . . . . . . . . . . . . Opening Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Output Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Interrupting Executing Callbacks . . . . . . . . . . . . . . . . . . . . . Controlling Interruptibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Event Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Event Processing During Callback Execution . . . . . . . . . . . . . 4-35 4-35 4-35 4-36 Controlling Figure Window Behavior . . . . . . . . . . . . . . . . . . 4-38 Using Modal Figure Windows . . . . . . . . . . . . . . . . . . . . . . . . . .
A GUI to Set Simulink Model Parameters . . . . . . . . . . . . . . Techniques Used in This Example . . . . . . . . . . . . . . . . . . . . . . View Completed Layout and Its GUI M-File . . . . . . . . . . . . . . How to Use the GUI (Text of GUI Help) . . . . . . . . . . . . . . . . . . Running the GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Programming the Slider and Edit Text Components . . . . . . . . Running the Simulation from the GUI . . . . . . . . . . . . . . . . . . .
1 Getting Started with GUIDE What Is GUIDE? (p. 1-2) An introduction to GUIDE Starting GUIDE (p. 1-3) How to start GUIDE and use the Quick Start dialog The Layout Editor (p. 1-4) The Layout Editor enables you to lay out the GUI components quickly and easily GUIDE Templates (p. 1-6) GUIDE templates are simple, pre-constructed GUIs that you can modify for your own purposes Running a GUI (p. 1-8) How to run a GUI GUI FIG-Files and M-Files (p.
1 Getting Started with GUIDE What Is GUIDE? GUIDE, the MATLAB® Graphical User Interface development environment, provides a set of tools for creating graphical user interfaces (GUIs). These tools greatly simplify the process of designing and building GUIs. You can use the GUIDE tools to • Lay out the GUI Using the GUIDE Layout Editor, you can lay out a GUI easily by clicking and dragging GUI components — such as panels, buttons, text fields, sliders, menus, and so on — into the layout area.
Starting GUIDE Starting GUIDE To start GUIDE, enter guide at the MATLAB prompt. This displays the GUIDE Quick Start dialog, as shown in the following figure. From the Quick Start dialog, you can • Create a new GUI from one of the GUIDE templates — prebuilt GUIs that you can modify for your own purposes. • Open an existing GUI. Once you have selected one of these options, clicking OK opens the GUI in the Layout Editor.
1 Getting Started with GUIDE The Layout Editor When you open a GUI in GUIDE, it is displayed in the Layout Editor, which is the control panel for all of the GUIDE tools. The following figure shows the Layout Editor with a blank GUI template. Layout Area Component Palette You can lay out your GUI by dragging components, such as push buttons, pop-up menus, or axes, from the component palette, at the left side of the Layout Editor, into the layout area.
The Layout Editor You can also use the Layout Editor to set basic properties of the GUI components. To learn more about the Layout Editor, see “Using the Layout Editor” on page 3-9. See “Laying Out the GUI” on page 2-3 for a detailed example of laying out a GUI.
1 Getting Started with GUIDE GUIDE Templates The GUIDE Quick Start dialog provides templates for several basic types of GUIs. The advantage of using templates is that often you can modify a template more quickly and easily than by starting from a blank GUI. When you select a template in the Templates pane, a preview of it appears in the right-hand pane. For example, when you select the GUI with Axes and Menu, the Quick Start dialog appears as in the following figure.
GUIDE Templates To display the names of the GUI components in the component palette, select Preferences from the File menu, check the box next to Show names in component palette, and click OK. Note that the Layout Editor does not display the functioning GUI. The next section describes how to run the actual GUI from the Layout Editor. To learn more about templates, see “Using GUIDE Templates” on page 3-2.
1 Getting Started with GUIDE Running a GUI To run a GUI, select Run from the Tools menu, or click the run button on the toolbar. This displays the functioning GUI outside the Layout Editor. For example, when you run the GUI with Axes and Menu template, it appears as shown in the following figure. This GUI displays various MATLAB plots. Select a plot from the pop-up menu and click Update.
GUI FIG-Files and M-Files GUI FIG-Files and M-Files GUIDE stores a GUI in two files, which are generated the first time you save or run the GUI: • A FIG-file, with extension .fig, which contains a complete description of the GUI layout and the components of the GUI: push buttons, menus, axes, and so on. • An M-file, with extension .m, which contains the code that controls the GUI, including the callbacks for its components. These two files correspond to the tasks of laying out and programming the GUI.
1 Getting Started with GUIDE Programming the GUI M-file After laying out your GUI, you can program the GUI M-file using the M-file editor. GUIDE automatically generates this file from your layout the first time you save or run the GUI.
Programming the GUI M-file You can view the callback for any of the GUI components by clicking the function icon on the toolbar. This displays a list of all the callbacks, as shown in the following figure. Clicking a callback on the list displays the section of the M-file containing the callback, where you can edit it. This example shows the callback template for pushbutton1_Callback. To learn more about programming the M-file, see Chapter 4, “Programming GUIs.
1 Getting Started with GUIDE Editing Version 5 GUIs with Version 7 GUIDE In MATLAB Version 5, GUIDE saved GUI layouts as MAT-file/M-file pairs. Since 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 as did M-files created in Version 5. Use the following procedure to edit a Version 5 GUI with Version 7 GUIDE: 1 Display the Version 5 GUI. 2 Obtain the handle of the GUI figure.
Editing Version 5 GUIs with Version 7 GUIDE M-file generated by Version 7 GUIDE can provide a model of how to restructure your code.
1 Getting Started with GUIDE 1-14
2 Creating a GUI Designing the GUI (p. 2-2) Designing the GUI before actually creating it in GUIDE. Laying Out the GUI (p. 2-3) Using the GUIDE Layout Editor to arrange the GUI components, such as push buttons, pop-up menus, and axes. Setting Properties for GUI Components (p. 2-11) Setting properties for each GUI component. Programming the GUI (p. 2-17) Using the M-file editor to program the GUI. Saving and Running a GUI (p. 2-26) Saving and running the GUI from the Layout Editor.
2 Creating a GUI Designing the GUI The GUI used in this example contains an axes that displays either a surface, mesh, or contour plot of data selected from the pop-up menu. The following picture shows a sketch that you might use as a starting point for the design. Plot Types Panel to group push buttons Surf Axes Mesh Push buttons to select plot type Contour Select Data peaks Menu for selecting data A panel contains three push buttons that enable you to select the type of plot you want.
Laying Out the GUI Laying Out the GUI This section illustrates how to lay out GUI components (i.e., a panel, axes, and user interface controls, such as push buttons, pop-up menus, static text, etc.) in the GUI. We recommend that you create the GUI for yourself, as this is the best way to learn how to use GUIDE.
2 Creating a GUI Open a New GUI in the Layout Editor Open GUIDE by typing guide at the MATLAB prompt. This displays the Guide Quick Start dialog shown in the following figure. If GUIDE is already open, you can display a similar dialog, by selecting New from the File menu. This dialog has no Open Existing GUI tab. In the Quick Start dialog, select the Blank GUI (default) template. Click OK to display the blank GUI in the Layout Editor, as shown in the following figure.
Laying Out the GUI To display the names of the GUI components in the component palette, select Preferences from the File menu, check the box next to Show names in component palette, and click OK. The Layout Editor then appears as shown in the following figure.
2 Creating a GUI Set the GUI Figure Size Specify the size of the GUI by resizing the grid area in the Layout Editor. Click on the lower-right corner and resize the grid until it is about 4-by-3 inches. Click corner to resize If you want to set the position or size of the GUI to an exact value, do the following: 1 Select Property Inspector from the View menu. 2 Select the button next to Units and then select inches from the pop-up menu 3 Click the + sign next to Position.
Laying Out the GUI Note Setting the Units property to characters gives the GUI a more consistent appearance across platforms. Add the Components 1 Add the panel and push buttons to the GUI. Select the following components from the component palette and drag them into the layout area: - A panel - Three push buttons Select the panel and move it to where it appears in the original sketch. Resize the panel to approximately 1-by-1.
2 Creating a GUI push buttons into the panel. As you move each push button into the panel, GUIDE highlights the panel to indicate that the panel is the potential parent of the push button. The following figure shows the highlight. Note Panels, button groups, and figures can all be parents of component objects and display this highlight when you move a component into them. 2 Add the remaining components to the GUI.
Laying Out the GUI Align the Components You can use the Alignment Tool to align components with respect to one another if they have the same parent. For example, to align the three push buttons: 1 Select all three push buttons by pressing Ctrl and clicking them. 2 Select Align Objects from the Tools menu to display the Alignment Tool. 3 Make the following settings in the Alignment Tool, as shown in the following figure: - 20 pixels spacing between push buttons in the vertical direction.
2 Creating a GUI Now align the tops of the axes and the panel. Note that when the panel moves, its contents move with it.
Setting Properties for GUI Components Setting Properties for GUI Components To set the properties of each GUI component, select the Property Inspector from the View menu to display the Property Inspector dialog box. When you select a component in the Layout Editor, the Property Inspector displays that component’s properties. If no component is selected, the Property Inspector displays the properties of the GUI figure.
2 Creating a GUI Title Property A panel’s Title property controls the title that appears at the top or bottom of the panel. Select the panel in the Layout Editor and then scroll down in the Property Inspector until you come to Title. In the field to the right of Title, change Panel to Plot Types. Use the TitlePosition property to control the position of the title.
Setting Properties for GUI Components When you click on the Layout Editor, the current layout of the GUI appears as in the following figure.
2 Creating a GUI Callback Properties Components use callbacks to do their work. A callback is a function that executes when a user performs a specific action such as clicking a push button, selecting a menu item, or pressing a keyboard key, or when a component is created or deleted. Each component and menu item has properties that specify its callbacks. When you create a GUI, you must program the callbacks you need to control operation of the GUI.
Setting Properties for GUI Components When you first add a component to a layout, GUIDE sets the value of Tag to a default string such as pushbutton1. If the component has a Callback property, GUIDE also sets the value of Callback to the string %automatic. The following figure shows an example. - ... When you save or run the GUI, GUIDE generates an M-file that includes stubs for the Callback functions for each component that has one.
2 Creating a GUI You can redefine the value of Tag to be more descriptive, but the value of each Tag property must be unique for a given GUI. In this example, change the Tag property of the pop-up menu to plot_pop-up before you save or run the GUI for the first time. The following figure shows the new Tag value. Set Tag to plot_popup When you save or run the GUI, GUIDE sets the name of the callback subfunction in the pop-up menu Callback property to plot_pop-up_Callback.
Programming the GUI Programming the GUI After laying out the GUI and setting component properties, the next step is to program it. This section explains how to do that.
2 Creating a GUI cursor to a specific callback by clicking the function icon on the toolbar, then selecting the callback you want in the pop-up menu that displays. Click the OpeningFcn Callback For example, clicking simple_gui_OpeningFcn moves the cursor to the opening function. The next topic explains how you can add code to the opening function to create data for the GUI or perform other tasks.
Programming the GUI Sharing Data Between Callbacks This topic describes the process for sharing data between callbacks in a GUI. Subsequent topics, “Adding Code to the Opening Function” on page 2-20 and “Adding Code to the Callbacks” on page 2-22, contain examples. You can share data between callbacks by storing the data in the MATLAB handles structure. All components in a GUI share the same handles structure. It is passed as an input argument to all callbacks generated by GUIDE.
2 Creating a GUI Note To save any changes that you make to the handles structure, you must use the command guidata(hObject,handles). It is not sufficient to just set the value of a handles field. To retrieve X in another callback, use the command X = handles.my_data; You can access the data in the handles structure in any callback because hObject and handles are input arguments for all the callbacks generated by GUIDE.
Programming the GUI % % % % % This function has no output args, see OutputFcn. hObject handle to figure eventdata reserved - to be defined in a future version of MATLAB handles structure with handles and user data (see GUIDATA) varargin command line arguments to untitled (see VARARGIN) Add this code Autogenerated code % 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; sinc = sin(r)./r; handles.sinc = sinc; handles.
2 Creating a GUI The following figure shows how the GUI now looks when it first displays. Adding Code to the Callbacks When the GUI is completed and running, and a user clicks a user interface control, such as a push button, MATLAB executes the callback specified by the component’s Callback property. In the example, the name of the Surf push button callback is surf_pushbutton_Callback. For information about the naming of callbacks see “The Tag Property” on page 2-14.
Programming the GUI Add the code after the comments following the function definition, as shown below: Surf push button callback: % --- Executes on button press in surf_pushbutton.
2 Creating a GUI Add this code to the Contour push button callback: % Display contour plot of the currently selected data contour(handles.current_data); Pop-up Menu Callback The pop-up menu enables users to select the data to plot. Every time a user selects one of the three plots, the pop-up menu callback reads the pop-up menu Value property to determine what item is currently displayed and sets handles.current_data accordingly.
Programming the GUI properties of each component of the GUI. Selecting the name of a component in the list also selects the component in the Layout Editor. For example, in the following figure, the uicontrol (mesh_pushbutton Mesh ) is selected in the Object Browser. The tag mesh_pushbutton corresponds to the callback mesh_pushbutton_Callback. Note that the corresponding component, the mesh push button, is also selected in the Layout Editor.
2 Creating a GUI Saving and Running a GUI After writing the callbacks, you can run the GUI by selecting Run from the Tools menu or clicking the Run button on the GUIDE toolbar. If you have not saved the GUI recently, GUIDE displays the following dialog box. If this happens, click Yes and then save the GUI files to a writable directory.
Saving and Running a GUI Note The name of the FIG-file saved by the Layout Editor and the generated M-file must match. See “Renaming GUI Files” if you want to rename files after first activating the GUI. Next, select membrane in the pop-up menu and click the Contour push button. The GUI should look like the following figure.
2 Creating a GUI Try experimenting with this GUI by adding another data set in the opening function, and a push button that displays a plot of the data set. Make sure to add the name of the new data set to the pop-up menu as well.
3 Laying Out GUIs and Setting Properties Using GUIDE Templates (p. 3-2) Overview of GUIDE templates — simple GUIs that you modify to create your own GUIs. Using the Layout Editor (p. 3-9) Add and arrange objects in the figure window. Selecting GUI Options (p. 3-25) Set the options for your GUI. Aligning Components in the Layout Editor (p. 3-34) Align objects with respect to each other. Setting Component Properties — The Property Inspector (p.
3 Laying Out GUIs and Setting Properties Using GUIDE Templates GUIDE provides several templates, which are simple examples that you can modify to create your own GUIs. The templates are fully functional GUIs: their callbacks are already programmed. You can view the code for these callbacks to see how they work, and then modify the callbacks for your own purposes. You can access the templates in two ways: • Start GUIDE by entering guide at the MATLAB prompt.
Using GUIDE Templates right pane. Clicking OK opens the GUI template in the Layout Editor. If you select Save on startup as and type in name in the field to the right, GUIDE saves the GUI before opening it in the Layout Editor. If you choose not to save the GUI at this point, GUIDE prompts you to save it the first time you run the GUI.
3 Laying Out GUIs and Setting Properties Select the blank GUI if the other templates are not suitable starting points for the GUI you are creating, or if you prefer to start with an empty GUI. GUI with Uicontrols The following figure shows the GUI with Uicontrols template displayed in the Layout Editor. When you run the GUI by clicking the Run icon in the following figure.
Using GUIDE Templates When a user enters values for the density and volume of an object, and clicks the Calculate button, the GUI calculates the mass of the object and displays the result next to Mass(D*V). GUI with Axes and Menu The GUI with axes and menu template is shown in the following figure. When you run the GUI by clicking the Run icon on the toolbar, the GUI displays a plot of five random numbers generated by the MATLAB rand(5) command, as shown in the following figure.
3 Laying Out GUIs and Setting Properties You can select other plots in the pop-up menu. Clicking the Update button displays the currently selected plot on the axes. The GUI also has a File menu with three items: • Selecting Open displays a dialog from which you can open files on your computer. • Selecting Print executes the printdlg command, which opens the Print dialog: printdlg(handles.figure1) Note that handles.figure1 contains the current plot. Clicking Yes in the Print dialog prints the plot.
Using GUIDE Templates Running the GUI displays the dialog shown in the following figure: The GUI returns the text string Yes or No, depending on which button you press. The GUI is blocking, which means that the current M-file stops executing until the GUI restores execution. You can make a GUI blocking by adding the following command to the opening function: uiwait(handles.
3 Laying Out GUIs and Setting Properties To restore access to other MATLAB windows once a button is clicked, add the following command to callbacks for both the Yes and No push buttons: uiresume(handles.figure1); The GUI is also modal, which means that the user cannot interact with other MATLAB windows until clicking one of the buttons. See “Using Modal Figure Windows” on page 4-38 for more information on making a GUI modal. Select this template if you want your GUI to return a string or to be modal.
Using the Layout Editor Using the Layout Editor The Layout Editor enables you to select GUI components from the component palette, at the left side of Layout Editor, and arrange them in the layout area, to the right. When you click the Run icon , the functioning GUI appears outside the Layout Editor.
3 Laying Out GUIs and Setting Properties Alignment Tool Menu Editor Tab Order Editor M-file Editor Property Inspector Object Browser Run Undo Redo Layout Area Component Palette Figure Resize Tab If you want to load an existing GUI for editing, type guide filename.fig or use Open from the File menu on the Layout Editor. Selecting Components from the Component Palette The component palette at the left of the Layout Editor contains the components that you can add to your GUI.
Using the Layout Editor After selecting the components for your GUI and placing them in the layout area, you need to set their properties and program their callbacks. The following sections describe how to do this: • “Setting Component Properties — The Property Inspector” on page 3-40 • “Programming Callbacks for GUI Components” on page 4-8 Push Button Push buttons generate an action when clicked. For example, an OK button might close a dialog box and apply settings.
3 Laying Out GUIs and Setting Properties single-line edit text, Ctl+Enter for a multi-line edit text, or the focus moves away. Static Text Static text controls display lines of text. Static text is typically used to label other controls, provide directions to the user, or indicate values associated with a slider. Users cannot change static text interactively and there is no way to invoke the callback routine associated with it.
Using the Layout Editor Button Group Button groups are like panels but can be used to manage exclusive selection behavior for radio buttons and toggle buttons. For radio buttons and toggle buttons that are managed by a button group, you must include the code to control them in the button group’s SelectionChangeFcn callback function, not in the individual uicontrol Callback functions. A button group overwrites the Callback properties of radio buttons and toggle buttons that it manages.
3 Laying Out GUIs and Setting Properties Adding a Component to a Panel or Button Group To add a component to a panel or button group, select the component in the component palette then move the cursor over the desired panel or button group. The position of the cursor determines the component’s parent. Notice that GUIDE highlights the potential parent as shown in the following figure.
Using the Layout Editor Highlight Cursor If the component is not entirely contained in the panel or button group, it appears to be clipped in the layout editor. When you run the GUI, the entire component is displayed and straddles the panel or button group border. The component is nevertheless a child of the panel and behaves accordingly.
3 Laying Out GUIs and Setting Properties You can use the Object Browser to determine the child objects of a panel or button group. “Viewing the Object Hierarchy — The Object Browser” on page 3-56 tells you how. Adding an ActiveX Control When you drag an ActiveX component from the component palette into the layout area, GUIDE opens a dialog that lists all the registered ActiveX controls on your system.
Using the Layout Editor Selecting Components You can select components in the layout area in the following ways. • Click a single component to select it. • Press Ctrl+A to select all child objects of the figure. This does not select components that are child objects of panels or button groups. • Click and drag the cursor to create a rectangle that encloses the components you want to select. If the rectangle encloses a panel or button group, only the panel or button group is selected, not its children.
3 Laying Out GUIs and Setting Properties panel, or button group from which you move them, even if they move outside its boundaries. Copying, Cutting, and Clearing Components Use standard menu and pop-up menu commands, toolbar icons, keyboard keys, and shortcut keys to copy, cut, and clear components. Copying. Copying places a copy of the selected components on the clipboard. A copy of a panel or button group includes its children. Cutting.
Using the Layout Editor • Right-click and drag the component to the desired location. The position of the cursor when you drop the components determines the parent of all the selected components. Look for the highlight as described in “Adding a Component to a Panel or Button Group” on page 3-14. Running the GUI To run the GUI you design in the Layout Editor, select Run in the Tools menu or click the Run icon on the toolbar.
3 Laying Out GUIs and Setting Properties Replace — writes over the existing file. Append — inserts new callbacks for components added since the last save and make changes to the code based on change made from the Application Options dialog. • If the directory in which you saved the GUI is not on the MATLAB path, GUIDE opens a dialog box with three options, as shown in the following figure. Change MATLAB current directory — changes the MATLAB current directory to the directory where you saved the GUI.
Using the Layout Editor Note GUIDE automatically saves both the M-file and the FIG-file when you run the GUI. 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 generates the M-file automatically when you save or run the figure. Renaming GUI Files Use Save As from the Layout Editor File menu to rename the GUI FIG-file.
3 Laying Out GUIs and Setting Properties 4 Save the exported M-file in the Save As dialog. By default, GUIDE gives the exported M-file the name of the GUI M-file with _export appended. Note If you save a large data set in the GUI figure or in a uicontrol, GUIDE might also export a MAT-file containing the data in addition to exporting an M-file. For example, the data could be saved in a figure or uicontrol UserData property, or in a figure Colormap property.
Using 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. Like the View menu in the Layout Editor, these context menus enable you to add a callback subfunction to your GUI M-file for any of the object properties that define callback routines. See “Callback Properties” on page 3-51 for more information.
3 Laying Out GUIs and Setting Properties Component Context Menus The following picture shows the context menu associated with user interface control components, as well as with axes, panels, and button groups. The callback properties listed in the View Callbacks submenu differ for different components.
Selecting GUI Options Selecting GUI Options After opening a new GUI template in the Layout Editor, but before saving the GUI, you can configure the GUI using the GUI Options dialog. Access the dialog by selecting GUI Options from the Layout Editor Tools menu. Configuring the GUI M-File The GUI Options dialog enables you to select whether you want GUIDE to generate only a FIG-file for your layout or both a FIG-file and an M-file. You can also select a number of different behaviors for your GUI.
3 Laying Out GUIs and Setting Properties 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. • Other (Use ResizeFcn) — Program the GUI to behave in a certain way when users resize the figure window.
Selecting GUI Options Property Settings. GUIDE sets the following properties to create proportional resizing GUIs: • Units properties of the axes, user interface controls, panels, and button groups are set to normalized so that these components resize and reposition as the figure window changes size. • Units property of the figure is set to characters so the GUI displays at the correct size at run-time, based on any changes in font size. • Resize figure property set to on (the default).
3 Laying Out GUIs and Setting Properties such as plot, that alter the current figure. With the default option, which is Callback (GUI becomes Current Figure within Callbacks), the GUI can become the MATLAB current figure, by the command gcf, only while a callback is executing. There may be occasions when you want the GUI figure handle to be accessible from the command line. For example, you might want the GUI to display plots created at the command line.
Selecting GUI Options 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. HandleVisibility — Off.
3 Laying Out GUIs and Setting Properties Generate Callback Function Prototypes When you select Generate callback function prototypes in the GUI Options dialog, GUIDE adds the most commonly used subfunctions to the GUI M-file for any component you add to the GUI. You must then write the code for the callback in this subfunction. GUIDE also adds a subfunction whenever you edit a callback routine from the Layout Editor’s right-click context menu and when you add menus to the GUI using the Menu Editor.
Selecting GUI Options function pushbutton1_Callback(hObject, eventdata, handles) Assigning a Callback Property String When you first add a component to your GUI layout, its Callback property is set to the string %automatic. This string signals GUIDE to replace it with one that calls the appropriate callback subfunction in the GUI M-file when you save or run the GUI.
3 Laying Out GUIs and Setting Properties GUI Allows Only One Instance to Run (Singleton) 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. If you allow only one instance, MATLAB reuses the existing GUI figure whenever the command to run the GUI is issued. If a GUI already exists, MATLAB brings it to the foreground rather than creating a new figure.
Selecting GUI Options Without system color matching With system color matching Generate FIG-File Only Select Generate FIG-file only in the GUI Options dialog if you do not want GUIDE to generate the M-file. When you save the GUI from the Layout Editor, GUIDE creates a FIG-file, which you can redisplay using the open 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.
3 Laying Out GUIs and Setting Properties Aligning Components in the Layout Editor You can select and drag any component or group of components that has the same parent 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.
Aligning Components in the Layout Editor The alignment tool provides two types of alignment operations: • 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.
3 Laying Out GUIs and Setting Properties Bounding box for the selected components 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 number of other values ranging from 10 to 200 pixels. You can optionally enable snap-to-grid, which causes any object that is moved or resized to within 9 pixels of a grid line to jump to that line. Snap-to-grid works with or without a visible grid.
3 Laying Out GUIs and Setting Properties 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 MATLAB figures maintain separate stacks that control the front-to-back positioning for different kinds of components: • User interface controls such as buttons, sliders, and pop-up menus • Panels, button groups, and axes • ActiveX controls You can control the front-to-back positioning
Aligning Components in the Layout Editor The Layout Editor provides four operations that enable you to control front-to-back positioning: • Bring to Front — move the selected object(s) in front of nonselected objects (available from the right-click context menu, the Layout menu, or the Ctrl+F shortcut). • Send to Back — move the selected object(s) behind nonselected objects (available from the right-click context menu, the Layout menu, or the Ctrl+B shortcut).
3 Laying Out GUIs and Setting Properties 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 To change a property, click in the field to the right of the property name, delete its current value, and type a new value. What Properties Do I Need to Set? The properties you need to set depend on the component. The property descriptions will help you decide which properties you need to set. For descriptions of each property, see the property reference pages for each kind of component. They are listed in the following table.
3 Laying Out GUIs and Setting Properties Component Property Reference Page Panel Uipanel Properties Button group Uibuttongroup Properties Menu Uimenu Properties Context menu (associated with a component using its Uicontextmenu property) Uicontextmenu Properties Some Commonly Used Properties As examples, this section describes four important and commonly used properties of user interface control components: Tag, Callback, String, and Value.
Setting Component Properties — The Property Inspector Callback The Callback property specifies the callback that is executed in the GUI M-file when a user activates the component. String The String property contains text for the component. The following are examples: • For buttons, check boxes, list boxes, edit text, and static text, the String text is displayed on or next to the component. • For an edit text, the String property contains a list of strings that is displayed in the text box.
3 Laying Out GUIs and Setting Properties Setting Radio Button Properties 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 (1 by default) • Value = Min, button is not selected (0 by default) To make radio buttons mutually exclusive within a group, the callback for each radio button must set the Value property to 0 on all other radio buttons in the group.
Setting Component Properties — The Property Inspector The Value property contains the index into the list of strings that corresponds to the selected item. If the user selects multiple items, then Value is a vector of indices. By default, the first item in the list is highlighted when the list box is first displayed. If you do not want any item highlighted, then set the Value property to empty, []. This works only when multiple selection is enabled.
3 Laying Out GUIs and Setting Properties Note If you have set units for your GUI to characters, certain combinations of width and height produce a slider with the opposite orientation from the intended. This is because a character is rectangular, i.e., it is higher than it is wide. 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.
Setting Component Properties — The Property Inspector The SliderStep property controls the amount the slider Value property changes when you click the mouse on the arrow button or on the slider trough. Specify SliderStep as a two-element vector. The default, [0.01 0.10], provides a 1 percent change for clicks on an arrow and a 10 percent change for clicks in the trough. The actual step size is a function of the slider step and the slider range. Designing a Slider.
3 Laying Out GUIs and Setting Properties Determining Which Item Is Selected. The Value property contains the index of the selected item. For example, if the String contains the three items, peaks, membrane, and sinc and the Value property has a value of 2, then the item selected is membrane. When not open, a pop-up 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.
Setting Component Properties — The Property Inspector • 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.
3 Laying Out GUIs and Setting Properties Set the following panel properties: • BorderType beveledout • BorderWidth 2 • HighlightColor (white) - red 1.0 - green 1.0 - blue 1.0 • ShadowColor (blue) - red 0.0 - green 0.0 - blue 1.
Setting Component Properties — The Property Inspector Callback Properties A callback is a function that executes when a user performs a specific action such as clicking a push button or pressing a keyboard key, or when a component is created or deleted. Each component and menu item has properties that specify its callbacks. When you create a GUI, you must program the callbacks you need to control operation of the GUI.
3 Laying Out GUIs and Setting Properties The following table lists the various callback properties and briefly describes the purpose of each callback. See the components’ property reference pages to find out which callbacks apply to a specific component. Callback Property Description ButtonDownFcn Executes when the user presses a mouse button while the pointer is on or within five pixels of a component. Callback Performs the primary work of the component.
Setting Component Properties — The Property Inspector • In the View menu, select View Callbacks. Then select the desired callback, e.g., KeyPressFcn. GUIDE adds the callback to the M-file, opens the M-file if it is not already open, and scrolls to the first line of the new callback. Changing Tag and Callback Properties This section discusses what you need to keep in mind if you change a component’s tag or the value of any of its callback properties.
3 Laying Out GUIs and Setting Properties Making the Change in the Property Editor. For example, to change the callback name in a push button’s callback property, select the push button in the Layout Editor and then select Property Inspector in the View menu. Scroll down in the Property Inspector until you come to Callback, as shown in the following figure. As shown, the callback property points to pushbutton1_Callback in the M-file.
Setting Component Properties — The Property Inspector • References in the M-file to the field of the handles structure that contains the component’s handle are updated.
3 Laying Out GUIs and Setting Properties 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. It also shows the child objects of the panel and a menu that was created. See “Creating Menus — The Menu Editor” on page 3-57. To determine a component’s place in the hierarchy, select it in the Layout Editor. It is automatically selected in the Object Browser.
Creating Menus — The Menu Editor Creating Menus — The Menu Editor MATLAB enables you to create two kinds of menus: • Menu bar objects — drop-down menus whose titles appear on the figure menu bar. • Context menu objects — pop up when users right-click on graphics objects. They are also known as shortcut menus. You can create both types of menus using the Menu Editor. Access the Menu Editor from the Tools menu or from the Layout Editor toolbar.
3 Laying Out GUIs and Setting Properties Defining Menus for the Menu Bar When you create a drop-down menu, MATLAB adds its title to the figure menu bar. You can then create menu items for that menu. Each menu item can have a cascading menu, also known as a submenu, and these items can have cascading menus, and so on. Creating a Menu The first step is to click the New Menu tool to create a drop-down menu.
Creating Menus — The Menu Editor Adding Items to a Menu Use the New Menu Item tool to define the menu items that are displayed in the drop-down menu.
3 Laying Out GUIs and Setting Properties For example, to add an Open menu item under File, select File then click the New Menu Item tool. Fill in the Label and Tag fields for the new menu item. You can also • Choose a keyboard accelerator for the menu item with the Accelerator pop-up menu. • Select the Separator above this item check box to display a separator above the menu item. • Select the Check mark this item check box to display a check next to the menu item when the menu is first opened.
Creating Menus — The Menu Editor To create additional drop-down menus, use the New Menu tool in the same way you did to create the File menu. For example, the following picture also shows an Edit drop-down menu. To create a cascading menu, select the menu item that will be the title for the cascading menu, then click the New Menu Item tool. In the example below, select Copy then click the New Menu Item tool.
3 Laying Out GUIs and Setting Properties When you run the GUI, the menu titles appear in the menu bar.
Creating Menus — The Menu Editor Menu Callbacks By default, the Callback text field in the Menu Editor is set to the string %automatic. This causes GUIDE to add the empty callback subfunction to the GUI M-file when you save or run the GUI. If you change this string before saving the GUI, GUIDE does not add a subfunction for that menu item. Note that if you click the View button before saving the GUI, GUIDE asks you to save the GUI.
3 Laying Out GUIs and Setting Properties Syntax of the Callback Subfunction The GUI M-file contains all callbacks for the GUI, including the menu callbacks. All generated callbacks use the same syntax. For example, the Select all menu item from the previous example has following callback string: MyGui('menu_edit_selectall_Callback',gcbo,[],guidata(gcbo)) where: • MyGui — is the name of the GUI M-file that launches the figure containing the menus.
Creating Menus — The Menu Editor This is the automatically generated callback subfunction that you see if you click the View button after saving the GUI, or if you edit the GUI M-file. function menu_edit_selectall_Callback(hObject, eventdata,...
3 Laying Out GUIs and Setting Properties 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). Adding Items to the Context Menu Create the items that will appear in the context menu using New Menu Item on the Menu Editor’s toolbar. When you select the menu item, the Menu Editor displays fields for you to enter the Label and Tag properties of the menu item.
Creating Menus — The Menu Editor You can also • Select the Separator above this item check box to display a separator above the menu item when the menu is first opened. • Select the Check mark this item check box to display a check next to the menu item when the menu is first opened. A check is particularly useful to indicate the current state of the menu item.
3 Laying Out GUIs and Setting Properties end This changes the value of the Checked property of the menu item from on to off or vice versa each time a user selects the menu item. If you set the axes to be visible when a user first opens the GUI, make sure to select the Check mark this item check box in the Menu Editor, so that a check will appear next to the Show axes menu item initially. • Select the Enable this item check box so that the user can select this item when the menu is first opened.
Setting the Tab Order — The Tab Order Editor Setting the Tab Order — The Tab Order Editor A GUI’s tab order is the order in which components of the GUI are selected when a user presses the Tab key on the keyboard. When you create a GUI, GUIDE sets the tab order at each level to be the order in which you add components to that level in the Layout Editor. This is often not the best order for the user. The tab order for each level is determined independently.
3 Laying Out GUIs and Setting Properties To examine and change the tab order of the panel components, click the panel background to select it, then select Tab Order Editor in the Tools menu of the Layout Editor. . The Tab Order Editor displays the panel’s components in their current tab order. To change the tab order, select a component and press the up or down arrow to move the component up or down in the list.
4 Programming GUIs Understanding the GUI M-File (p. 4-2) The GUI M-file programs the GUI. This section describes the functioning of the GUI M-file, both the generated and user-written code. Programming Callbacks for GUI Components (p. 4-8) Explains how to program the callbacks for some specific GUI components. Managing GUI Data with the Handles Structure (p. 4-26) The handles structure provides easy access to all component handles in the GUI.
4 Programming GUIs Understanding the GUI M-File The GUI M-file generated by GUIDE controls the GUI and determines how it responds to a user’s action, such as pressing a push button or selecting a menu item. The M-file contains all the code needed to run the GUI, including the callbacks for the GUI components. While GUIDE generates the framework for this M-file, you must program the callbacks, which are subfunctions of the M-file, to perform the functions you want them to.
Understanding the GUI M-File You can retrieve the data in any other callback with the command X = handles.current_data; For an example of sharing data between callbacks, see “Example: Passing Data Between Callbacks” on page 4-26. For more information about handles, see “Managing GUI Data with the Handles Structure” on page 4-26. Accessing GUI Data You can access any of the data for the GUI components from the handles structure.
4 Programming GUIs • Callbacks — execute each time the user activates the corresponding component of the GUI.
Understanding the GUI M-File my_gui('Position', [71.8 44.9 74.8 19.7]) opens the GUI at the specified position, since Position is a valid figure property. If the input argument is not a valid figure property, you must add code to the opening function to make use of the argument. For an example, look at the opening function for the modal question dialog template.
4 Programming GUIs For example, if the GUI contains a push button whose String property is 'Yes', add the following code to its callback to make the GUI return 'Yes' when the user presses the push button: handles.output = 'Yes'; guidata(hObject, handles); uiresume; See the section “Managing GUI Data with the Handles Structure” on page 4-26 for more information about passing data with the handles structure.
Understanding the GUI M-File Input and Output Arguments The following examples illustrate various ways to call a GUI named my_gui with different arguments. All arguments are passed to the opening function in the GUI M-file. • Calling my_gui with no arguments opens my_gui. • Calling H = my_gui opens my_gui and returns the handle to my_gui. • Calling my_gui('Property', Value,...), where 'Property' is a valid figure property, opens my_gui using the given property-value pair.
4 Programming GUIs Programming Callbacks for GUI Components This section explains how to program the callbacks for some specific GUI components. “Callback Properties” on page 3-51 describes the different kinds of callbacks. See a component’s property reference page to determine which callbacks apply for that component. “Setting Component Properties — The Property Inspector” on page 3-40 provides links to the property reference pages.
Programming Callbacks for GUI Components % toggle button is pressed elseif button_state == get(hObject,'Min') % toggle button is not pressed end Note If you have toggle buttons that are managed by a button group component, you must include the code to control them in the button group’s SelectionChangeFcn callback function, not in the individual toggle button Callback functions. A button group overwrites the Callback properties of radio buttons and toggle buttons that it manages.
4 Programming GUIs Note If you have radio buttons that are managed by a button group component, you must include the code to control them in the button group’s SelectionChangeFcn callback function, not in the individual radio button Callback functions. A button group overwrites the Callback properties of radio buttons and toggle buttons that it manages. See “Button Groups” on page 4-13 for more information.
Programming Callbacks for GUI Components 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 whether the converted value is NaN (isnan), indicating the user entered a nonnumeric character and displays an error dialog (errordlg).
4 Programming GUIs callback can query the Selection Type property to determine if it was a singleor double-click. List Box Examples See the following examples for more information on using list boxes: • “List Box Directory Reader” on page 5-9 — Shows how to creates a GUI that displays the contents of directories in a list box and enables users to open a variety of file types by double-clicking on the filename.
Programming Callbacks for GUI Components % proceed with callback... Panels Panels group GUI components and can make a user interface easier to understand by visually grouping related controls. Panel children can be panels and button groups as well as axes and user interface controls. The position of each component within a panel is interpreted relative to the panel. If the panel is resized, you may want to reposition its components.
4 Programming GUIs radio button. It then uses the Tag property of the selected object to choose the appropriate code to execute.
Programming Callbacks for GUI Components Note If your GUI is opened as the result of another GUI’s callback, you might need to explicitly specify the target axes. See “GUIs with Multiple Axes” on page 4-16. Example: Displaying an Image on an Axes This example shows how to display an image on an axes. The example • Displays an image file on an axes. • Resizes the axes to fit the image. • Resizes the GUI so that its width and height are 100 pixels larger than the image file.
4 Programming GUIs The preceding code performs the following operations: • Reads the image file banner.jpg using the command imread. • Determines the size of the image file in pixels using the command imfinfo. • Sets the width and height of the GUI to be 100 pixels greater than the corresponding dimensions of the image file, which are stored as info.Width and info.Height, respectively. The width and height of the GUI are the third and fourth entries of the vector position.
Programming Callbacks for GUI Components ActiveX Controls You can insert an ActiveX control into your GUI if you are running MATLAB on Microsoft Windows. When you drag an ActiveX component from the component palette into the layout area, GUIDE displays a dialog in which you can select any registered ActiveX control on your system. When you select an ActiveX control and click Create, the control appears as a small box in the Layout Editor. You can then program the control to do what you want it to.
4 Programming GUIs 2 Scroll down the ActiveX Control List and select Mwsamp Control. This displays a preview of the ActiveX control Mwsamp, as shown in the following figure. 3 Click Create to display the ActiveX control in the Layout Editor, and resize the control to approximately the size of the square shown in the preview pane. You can do this by clicking and dragging a corner of the control, as shown in the following figure.
Programming Callbacks for GUI Components Resize the control by clicking and dragging 4 Click the Run button on the toolbar and save the GUI when prompted. GUIDE displays the GUI shown in the following figure.
4 Programming GUIs from the View menu. This displays the Property Inspector, as shown in the following figure.
Programming Callbacks for GUI Components refresh(handles.figure1); 4 Add the following command to the opening function: handles.activex1.label = ... ['Radius = ' num2str(handles.activex1.radius)]; 5 Run the GUI. Now, each time you click the ActiveX control, the radius of the circle is reduced by 10 percent and the new value of the radius is displayed, as shown in the following figure. G GUI After Clicking the Circle Six Times If you click the GUI enough times, the circle disappears entirely.
4 Programming GUIs handles.activex1.radius = ... get(hObject, 'Value')*handles.default_radius; handles.activex1.label = ... ['Radius = ' num2str(handles.activex1.radius)]; refresh(handles.figure1); 4 Add the following command to the opening function: handles.default_radius = handles.activex1.radius; 5 Add the following command at the end of the code in the activex1_Click callback: set(handles.slider1, 'Value', ... hObject.radius/handles.default_radius); 6 Run the GUI.
Programming Callbacks for GUI Components - Gets the Value of the slider, which in this example is a number between 0 and 1, the default values of the slider’s Min and Max properties. - Sets handles.activex1.radius equal to the Value times the default radius. Note that clicking the ActiveX control causes the slider to change position corresponding to the new value of the radius. The command set(handles.slider1, 'Value', ... hObject.radius/handles.
4 Programming GUIs Alternatively, you can enter methods(hObject) which displays the available methods in the Command Window. For more information about methods for ActiveX controls, see Invoking Methods in the online MATLAB documentation. See the reference pages for methodsview and methods for more information about these functions. Figures Figures are the windows that contain the GUIs you design with the Layout Editor.
Programming Callbacks for GUI Components hidden from plotting commands issued by your GUI. To issue plotting commands from your GUI, • Create a figure and axes. • Save the handle of the figure in the handles structure. • Create an axes, save its handle, and set its Parent property to the figure handle. • Create the plot, save the handles, and set their Parent properties to the handle of the axes. The following code illustrates these steps: fHandle = figure('HandleVisibility','off','IntegerHandle','off',...
4 Programming GUIs Managing GUI Data with the Handles Structure GUIDE provides a mechanism, called the handles structure, for storing and retrieving shared data using the same structure that contains the GUI component handles. The handles structure, which contains the handles of all the components in the GUI, is passed to each callback in the GUI M-file. Therefore, this structure is useful for saving any shared data. The following example illustrates this technique.
Managing GUI Data with the Handles Structure Defining the Data Fields in the Opening Function The GUI records the number of times a user enters an erroneous value in the text box and stores this number in a field of the handles structure. You can define this field, called number_errors, in the opening function as follows: handles.number_errors = 0; Type this command before the following line, which GUIDE automatically inserts into the opening function.
4 Programming GUIs num2str(get(handles.slider1,'Value'))); The code combines three commands: • The get command obtains the current value of the slider. • The num2str command converts the value to a string. • The set command resets the String property of the edit text to the updated value. Setting the Slider Value from the Edit Text Callback The edit text callback sets the slider’s value to the number the user types in, after checking to see if it is a single numeric value between 0 and 1.
Managing GUI Data with the Handles Structure Application Data Application 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 GUI M-file uses application data to store the handles structure. When using the GUIDE-generated M-file, it is simpler to use guidata than to access application data directly.
4 Programming GUIs 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.
Designing for Cross-Platform Compatibility 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.
4 Programming GUIs 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.
Types of Callbacks Types of Callbacks The primary mechanism for implementing a GUI is programming the callbacks of the GUI components used to build the interface. Callback Properties for All Graphics Objects All graphics objects have three properties that enable you to define callback routines: • ButtonDownFcn — MATLAB executes this callback when users click the left mouse button and the cursor is over the object or within a five-pixel border around the object.
4 Programming GUIs Callbacks for Specific Components Some components have additional properties that execute callback routines with the appropriate user action: • Callback — MATLAB executes the specified callback when a user activates a user interface control (uicontrol) or menu (uimenu) object, for example, when a user presses a push button or selects a menu item. • KeyPressFcn — MATLAB executes the specified callback when a user presses a key and the callback’s component has focus.
Interrupting Executing Callbacks 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.
4 Programming GUIs • 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.
Interrupting Executing Callbacks 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.
4 Programming GUIs Controlling 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 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. Perhaps this tool operates on only one figure at a time so you need a new instance of this tool for each graph.
Controlling Figure Window Behavior the initialization section of the GUI M-file in the opening function with the set command. set(hObject,'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. delete(handles.figure1) • Make the figure invisible. set(handles.figure1,'Visible','off') • Change the figure’s WindowStyle property to normal. set(handles.
4 Programming GUIs Example: Using the Modal Dialog to Confirm an Operation This example illustrates how to use the modal dialog GUI together with another GUI that has a Close button. Clicking the Close button displays the modal dialog, which asks users to confirm that they really want to proceed with the close operation. The following figure illustrates the dialog positioned over the GUI application, awaiting the user’s response.
Example: Using the Modal Dialog to Confirm an Operation Note The following links execute MATLAB commands and are designed to work within the MATLAB Help browser. If you are reading this online or in PDF, you should go to the corresponding section in the MATLAB Help Browser to use the links. • Click here to display the GUIs in the Layout Editor. • Click here to display the GUI M-files in the editor.
4 Programming GUIs Setting Up the GUI with the Close Button To set up the second GUI with a Close button, do the following: 1 Select New from the File menu in the GUIDE Layout Editor. 2 In the GUIDE Quick Start dialog, select Blank GUI (Default) and click OK. This opens the blank GUI in a new Layout Editor window. 3 Drag a push button from the Component palette of the Layout Editor into the layout area. 4 Right-click the push button and select Property Inspector from the pop-up menu.
Example: Using the Modal Dialog to Confirm an Operation % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) 9 After these comments, add the following code: % Get the current position of the GUI from the handles structure % to pass to the modal dialog. pos_size = get(handles.figure1,'Position'); % Call modaldlg with the argument 'Position'.
4 Programming GUIs Clicking the Yes button closes both the close dialog and the GUI that calls it. Clicking the No button closes just the dialog. How the GUI and Dialog Work This section describes what occurs when you click the Close button on the GUI: 1 User clicks the Close button. Its callback then - Gets the current position of the GUI from the handles structure with the command pos_size = get(handles.
Example: Using the Modal Dialog to Confirm an Operation 4 When a user clicks one of the two push buttons, the callback for the push button - Updates the output field in the handles structure - Executes uiresume to return control to the opening function where uiwait is called. 5 The output function is called, which returns the string Yes or No as an output argument, and deletes the dialog with the command delete(handles.
4 Programming GUIs 4-46
5 GUI Applications GUI with Multiple Axes (p. 5-2) Analyze data and generate frequency and time domain plots in the GUI figure. List Box Directory Reader (p. 5-9) List the contents of a directory, navigate to other directories, and define what command to execute when users double-click on a given type of file. Accessing Workspace Variables from a List Box (p. 5-15) List variables in the base MATLAB workspace from a GUI and plot them.
5 GUI Applications 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.
GUI with Multiple Axes View Completed Layout and Its GUI M-File If you are reading this in the MATLAB Help browser, you can click 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 GUI Applications To create the default values, set the String property of the edit text. The following figure shows the value set for the time vector. 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.
GUI with Multiple Axes 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 “Managing GUI Data with the Handles Structure” on page 4-26 for more information on the handles structure. See “Plot Push Button Callback” on page 5-6 for the details of how to use the handle to specify the target axes.
5 GUI Applications like you would on the command line. Note that Callback is the default setting for command-line accessibility. See “Selecting GUI Options” on page 3-25 for more information. 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 GUI M-file.
GUI with Multiple Axes • 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.
5 GUI Applications plot(t,x) set(handles.
List Box Directory Reader 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 (..
5 GUI Applications Note The following links execute MATLAB commands and are designed to work within the MATLAB Help browser. If you are reading this online or in PDF, you should go to the corresponding section in the MATLAB Help Browser to use the links. • Click here to display this GUI in the Layout Editor. • Click here to display the GUI M-file in the editor.
List Box Directory Reader • First input argument is not a directory, but is a character string and there is more than one argument — execute the subfunction identified by the argument (execute callback). The following code listing show the setup section of the GUI M-file, which does one the following: • Sets the list box directory to the current directory, if no directory is specified. • Changes the current directory, if a directory is specified.
5 GUI Applications • 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. dir returns a structure (dir_struct) with two fields, name and isdir, which contain this information.
List Box Directory Reader 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. However, the callback treats FIG-files differently. Instead of opening the FIG-file, it passes it to the guide command for editing.
5 GUI Applications 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.sorted_index(index_selected)) % If directory cd (filename) load_listbox(pwd,handles) % Load list box with new directory else [path,name,ext,ver] = fileparts(filename); switch ext case '.
Accessing Workspace Variables from a List Box 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.
5 GUI Applications • Delete the string assigned to the list box Callback property. View Completed Layout and Its GUI M-File If you are reading this in the MATLAB Help browser, you can click 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.
Accessing Workspace Variables from a List Box 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, or 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.
5 GUI Applications 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.
A GUI to Set Simulink Model Parameters 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.
5 GUI Applications 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. Note The following links execute MATLAB commands and are designed to work within the MATLAB Help browser. If you are reading this online or in PDF, you should go to the corresponding section in the MATLAB Help Browser to use the links. • Click here to display this GUI in the Layout Editor.
A GUI to Set Simulink Model Parameters Running the Simulation Once you have set the gain values, you can run the simulation by clicking the Simulate and store results button. The simulation time and output vectors are stored in the Results list. 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.
5 GUI Applications • Determine if the model is open (find_system). • Open the block diagram for the model and the subsystem where the parameters are being set, if not open already (open_system). • 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.
A GUI to Set Simulink Model Parameters • Calls model_open to ensure that the Simulink model is open so that simulation parameters can be set. • Gets the new slider value. • 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.
5 GUI Applications • Sets the appropriate block parameter to the new value (set_param). Here is the callback for the Kf Current value text box.
A GUI to Set Simulink Model Parameters Here is the Simulate and store results button callback. function SimulateButton_Callback(hObject, eventdata, handles) [timeVector,stateVector,outputVector] = sim('f14'); % Retrieve old results data structure if isfield(handles,'ResultsData') & ~isempty(handles.ResultsData) ResultsData = handles.ResultsData; % Determine the maximum run number currently used. maxNum = ResultsData(length(ResultsData)).
5 GUI Applications end set(handles.ResultsList,'String',ResultsStr); % Store the new ResultsData handles.ResultsData = ResultsData; guidata(hObject, handles) Removing Results from the List Box The GUI Remove button callback deletes any selected item from the Results list list box. It also deletes the corresponding run data from the handles structure.
A GUI to Set Simulink Model Parameters set(handles.ResultsList,'Value',currentVal,'String',resultsStr) % Store the new ResultsData guidata(hObject, handles) Plotting the Results Data The GUI Plot button callback creates a plot of the run data and adds a legend. The data to plot is passed to the callback in the handles structure, which also contains the gain settings used when the simulation ran.
5 GUI Applications currentVal = get(handles.ResultsList,'Value'); % Get data to plot and generate command string with color % specified legendStr = cell(length(currentVal),1); plotColor = {'b','g','r','c','m','y','k'}; for ctVal = 1:length(currentVal); PlotData{(ctVal*3)-2} = handles.ResultsData(currentVal(ctVal)).timeVector; PlotData{(ctVal*3)-1} = handles.ResultsData(currentVal(ctVal)).
A GUI to Set Simulink Model Parameters The GUI Help Button The GUI Help button callback displays an HTML file in the MATLAB Help browser. It uses two commands: • The which command returns the full path to the file when it is on the MATLAB path • The web command displays the file in the Help browser. This is the Help button callback. function HelpButton_Callback(hObject, eventdata, handles) HelpPath = which('f14ex_help.
5 GUI Applications when you add the list box and automatically sets the Callback property to execute this subfunction whenever the callback is triggered (which happens when users select an item in the list box). In this case, there is no need for the list box callback to execute, so you should delete it from the GUI M-file. It is important to remember to also delete the Callback property string so MATLAB does not attempt to execute the callback.
An Address Book Reader 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.
5 GUI Applications • 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 “Sharing Data with the Handles Structure” on page 4-2 for background information on this structure.
An Address Book Reader • GUI M-file options selected: Generate callback function prototypes Application allows only one instance to run Calling the GUI You can call the GUI M-file with no arguments, in which case the GUI uses the default address book MAT-file, or you can specify an alternate MAT-file from which the GUI reads information. In this example, the user calls the GUI with a pair of arguments, address_book('book', 'my_list.mat').
5 GUI Applications elseif (length(varargin) == 2 & strcmpi(varargin{1},'book') & (2 == exist(varargin{2},'file'))) Check_And_Load(varargin{2},handles); else errordlg('File Not Found','File Load Error') set(handles.Contact_Name,'String','') set(handles.Contact_Phone,'String','') 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 running the GUI, you can specify a MAT-file as an argument.
An Address Book Reader Check_And_Load Code Listing This is the Check_And_Load function. function pass = Check_And_Load(file,handles) % Initialize the variable "pass" to determine if this is a valid % file. pass = 0; % 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.
5 GUI Applications else errordlg('Not a valid Address Book','Address Book Error') end The Open Menu Callback The address book GUI contains a File menu that has an Open submenu for loading address book MAT-files. When selected, Open displays a dialog (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.
An Address Book Reader • If the name exists in the current address book, the corresponding phone number is displayed. • If the name does not exist, a question dialog (questdlg) asks you if you want to create a new entry or cancel and return to the name previously displayed. • If you create a new entry, you must save the MAT-file with the File -> Save menu.
5 GUI Applications return end end % If it's a new name, ask to create a new entry Answer=questdlg('Do you want to create a new entry?', ... 'Create New Entry', ... '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(hObject, handles) return case 'Cancel' % Revert back to the original number set(handles.
An Address Book Reader Code Listing function Contact_Phone_Callback(hObject, eventdata, handles) Current_Phone = get(handles.Contact_Phone,'string'); % If either one is empty then return if isempty(Current_Phone) return end % Get the current list of addresses from the handles structure Addresses = handles.Addresses; Answer=questdlg('Do you want to change the phone number?', ... 'Change Phone Number', ...
5 GUI Applications Determining Which Button Is Clicked The callback defines an additional argument, str, that indicates which button, Prev or Next, was clicked. For the Prev button Callback property (illustrated above), the Callback string includes 'Prev' as the last argument. The Next 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).
An Address Book Reader % last element in the Addresses array if i < 1 i = length(Addresses); end case 'Next' % Increase the index by one i = index + 1; % If the index is greater than the size of the array then point % to the first item in the Addresses array if i > length(Addresses) i = 1; end end % Get the appropriate data for the index in selected Current_Name = Addresses(i).Name; Current_Phone = Addresses(i).Phone; set(handles.Contact_Name,'string',Current_Name) set(handles.
5 GUI Applications Saving the MAT-File If the user selects Save, the save command is called to save the current MAT-file with the new names and phone numbers. If the user selects Save As, a dialog is displayed (uiputfile) that enables the user to select the name of an existing MAT-file or specify a new file. The dialog returns the selected filename and path. The final steps include • Using fullfile to create a platform-independent pathname. • Calling save to save the new data in the MAT-file.
An Address Book Reader end end The Create New Menu The Create New menu simply clears the Contact Name and Contact Phone # text fields to facilitate adding a new name and number. After making the new entries, the user must then save the address book with the Save or Save As menus. This callback sets the text String properties to empty strings: function New_Callback(hObject, eventdata, handles) set(handles.Contact_Name,'String','') set(handles.
5 GUI Applications The size of the Contact Name text box changes in proportion to the new figure width. This is accomplished by: • Changing the Units of the text box to normalized. • Resetting the width of the text box to be 78.9% of the figure’s width. • Returning the Units to characters. If the new width is less than the original width, use the original width. Changing the Height If the user attempts to change the height, use the original height.
An Address Book Reader if Figure_Size(3) < Original_Size(3) % If the width is too small then reset to origianl width set(hObject, 'Position',... [Figure_Size(1) Figure_Size(2) Original_Size(3) Original_Size(4)]) Figure_Size = get(hObject, 'Position'); end if Figure_Size(4) ~= Original_Size(4) % Do not allow the height to change set(hObject, 'Position',... [Figure_Size(1), Figure_Size(2)+Figure_Size(4)-Original_Size(4),...
5 GUI Applications 5-46
Index A activate figure 3-19 ActiveX controls 4-17 aligning GUI components 3-34 Alignment Tool, for GUIs 3-34 application data 4-29 application M-file 4-2 application options 3-25 axes multiple in GUI 5-2 axes, plotting when hidden 5-27 B button groups 3-13 adding components 3-14 C callback arguments 3-31 callback syntax 3-30 callbacks adding to GUI M-file in GUIDE 3-52 interrupting 4-35 types 4-33 check boxes 4-10 color of GUI background 3-32 command-line accessibility of GUIs 3-27 context menus associat
Index GUIDE (continued) creating menus 3-57 demonstration 2-3 editing version 5 GUIs 1-12 generated M-file 3-29 grids and rulers 3-36 GUI background color 3-32 handles structure and global data 4-26 introduction 1-2 layout tools 3-1 programming the GUI 4-1 Property Inspector 3-40 resizing GUIs 3-26 setting properties 3-40 H handles structure 4-26 help button for GUIs 5-29 hidden figure, accessing 5-27 L Layout Editor 3-9 controls 1-4 Layout Tools, GUI 3-1 list box example 5-9 list boxes 3-44, 4-11 M Men
Index T toggle buttons 4-8 toolbar menus creating with GUIDE 3-58 Index-3
Index Index-4