MATLAB® Creating Graphical User Interfaces R2012a
How to Contact MathWorks Web Newsgroup www.mathworks.com/contact_TS.html Technical Support www.mathworks.com comp.soft-sys.matlab suggest@mathworks.com bugs@mathworks.com doc@mathworks.com service@mathworks.com info@mathworks.com 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.
Revision History November 2000 June 2001 July 2002 June 2004 October 2004 March 2005 September 2005 March 2006 May 2006 September 2006 March 2007 September 2007 March 2008 October 2008 March 2009 September 2009 March 2010 September 2010 April 2011 September 2011 March 2012 Online Online Online Online Online Online Online Online Online Online Online Online Online Online Online Online Online Online Online Online Online Only Only Only Only Only Only Only Only Only Only Only Only Only Only Only Only Only Onl
Contents Introduction to Creating GUIs About GUIs in MATLAB Software 1 .................................... 1-2 How Does a GUI Work? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4 Where Do I Start? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6 Ways to Build MATLAB GUIs . . . . . . . . . . . . . . . . . . . . . . . 1-8 What Is a GUI? How to Create a GUI with GUIDE 2 Introduction to GUIDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Save the GUI Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-25 Program the Simple GUIDE GUI . . . . . . . . . . . . . . . . . . . . Add Code to the Simple GUIDE GUI . . . . . . . . . . . . . . . . . . Generate Data to Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Program the Pop-Up Menu . . . . . . . . . . . . . . . . . . . . . . . . . . Program the Push Buttons . . . . . . . . . . . . . . . . . . . . . . . . . .
Create GUIs with GUIDE What Is GUIDE? 4 GUIDE: Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . GUI Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . GUI Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2 4-2 4-2 GUIDE Tools Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3 GUIDE Preferences and Options 5 GUIDE Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Select a GUI Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Access the Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Template Descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6 6-6 6-7 Set the GUI Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Maximize the Layout Area . . . . . . . . . . . . . . . . . . . . . . . . . . 6-15 6-18 Add Components to the GUI . . . . . . . . . . . . . . . . . . . . . . . .
Standard Background Color . . . . . . . . . . . . . . . . . . . . . . . . . 6-138 Cross-Platform Compatible Units . . . . . . . . . . . . . . . . . . . . 6-139 Save and Run a GUIDE GUI 7 Name a GUI and Its Files . . . . . . . . . . . . . . . . . . . . . . . . . . . The GUI Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . File and GUI Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Rename GUIs and GUI Files . . . . . . . . . . . . . . . . . . . . . . . .
Adding Callback Templates to an Existing GUI Code File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . About GUIDE-Generated Callbacks . . . . . . . . . . . . . . . . . . 8-9 8-9 Default Callback Properties in GUIDE . . . . . . . . . . . . . . . Setting Callback Properties Automatically . . . . . . . . . . . . . Deleting Callbacks from a GUI Code File . . . . . . . . . . . . . . 8-11 8-11 8-14 Customizing Callbacks in GUIDE . . . . . . . . . . . . . . . . . . .
Data Management Mechanism Summary . . . . . . . . . . . . . . Nested Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UserData Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Application Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . GUI Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Examples of Sharing Data Among a GUI’s Callbacks . . . .
About the List Box Directory Example . . . . . . . . . . . . . . . . 10-54 View and Run the List Box Directory GUI . . . . . . . . . . . . . 10-55 Implement the List Box Directory GUI . . . . . . . . . . . . . . . . 10-56 xii Contents Access Workspace Variables from a List Box (GUIDE) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . About the Workspace Variable Example . . . . . . . . . . . . . . . View and Run the Workspace Variable GUI . . . . . . . . . . . .
Run the Close-Confirmation GUI . . . . . . . . . . . . . . . . . . . . . 10-102 How the Close-Confirmation GUIs Work . . . . . . . . . . . . . . 10-103 Time Data Updates from a GUI (GUIDE) . . . . . . . . . . . . . About the Timer GUI Example . . . . . . . . . . . . . . . . . . . . . . View and Run the GUIDE Timer GUI . . . . . . . . . . . . . . . . . Components Used by the Timer GUI . . . . . . . . . . . . . . . . . . How the GUI Implements the Timer . . . . . . . . . . . . . . . . . .
Set Tab Order in a Programmatic GUI . . . . . . . . . . . . . . . How Tabbing Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Default Tab Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Change the Tab Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-70 11-70 11-70 11-73 Create Menus for a Programmatic GUI . . . . . . . . . . . . . . 11-75 Add Menu Bar Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Program ActiveX Controls . . . . . . . . . . . . . . . . . . . . . . . . . . 12-34 Program Menu Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-34 Program Toolbar Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-37 Manage Application-Defined Data 13 Ways to Manage Data in a Programmatic GUI . . . . . . . . Data Management Mechanism Summary . . . . . . . . . . . . . . Nested Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
GUI with Axes, Menu, and Toolbar . . . . . . . . . . . . . . . . . . 15-4 About the Axes, Menu, and Toolbar Example . . . . . . . . . . . 15-4 View and Run the AxesMenuToolbar Code . . . . . . . . . . . . . 15-6 Generate the Graphing Commands and Data . . . . . . . . . . . 15-7 Create the GUI and Its Components . . . . . . . . . . . . . . . . . . 15-8 Initialize the GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-13 Define the Callbacks . . . . . . . . . . . . . . . . . . . . . . .
Examples A Simple Examples (GUIDE) . . . . . . . . . . . . . . . . . . . . . . . . . . A-2 Simple Examples (Programmatic) . . . . . . . . . . . . . . . . . . . A-3 Application Examples (GUIDE) . . . . . . . . . . . . . . . . . . . . . A-4 Programming GUI Components (GUIDE) . . . . . . . . . . . . A-5 Application-Defined Data (GUIDE) . . . . . . . . . . . . . . . . . . A-6 GUI Layout (Programmatic) . . . . . . . . . . . . . . . . . . . . . . . . A-7 Programming GUI Components (Programmatic) . .
xviii Contents
Introduction to Creating GUIs Chapter 1, About GUIs in MATLAB Software (p. 1-1) Explains what a GUI is, how a GUI works, and how to get started creating a GUI. Chapter 2, How to Create a GUI with GUIDE (p. 2-1) Steps you through the process of creating a simple GUI using GUIDE. Chapter 3, How to Create a Simple GUI Programmatically (p. 3-1) Steps you through the process of creating a simple GUI programmatically.
1 About GUIs in MATLAB Software • “What Is a GUI?” on page 1-2 • “How Does a GUI Work?” on page 1-4 • “Where Do I Start?” on page 1-6 • “Ways to Build MATLAB GUIs” on page 1-8
1 About GUIs in MATLAB® Software What Is a GUI? A graphical user interface (GUI) is a graphical display in one or more windows containing controls, called components, that enable a user to perform interactive tasks. The user of the GUI does not have to create a script or type commands at the command line to accomplish the tasks. Unlike coding programs to accomplish tasks, the user of a GUI need not understand the details of how the tasks are performed.
What Is a GUI? • Three buttons that provide different kinds of plots: surface, mesh, and contour When you click a push button, the axes component displays the selected data set using the specified type of 3-D plot.
1 About GUIs in MATLAB® Software How Does a GUI Work? In the GUI described in “What Is a GUI?” on page 1-2, the user selects a data set from the pop-up menu, then clicks one of the plot type buttons. The mouse click invokes a function that plots the selected data in the axes. Most GUIs wait for their user to manipulate a control, and then respond to each action in turn.
How Does a GUI Work? running at those times. This distinguishes event-driven programming from other types of control flow, for example, processing sequential data files.
1 About GUIs in MATLAB® Software Where Do I Start? Before starting to construct a GUI you have to design it. At a minimum, you have to decide: • Who the GUI users will be • What you want the GUI to do • How users will interact with the GUI • What components the GUI requires to function When designing any software, you need to understand the purposes a new GUI needs to satisfy.
Where Do I Start? Designing a Graphical User Interface Understand Requirements Purpose Use c a s e s Interactivity Functionality Specify GUI(s) Inputs Controls Displays Behavior Outputs Yes Add another window or dialog? No mock-up or prototype Design GUI(s) Sequencing Grouping Labeling Styling Iterate as needed Generate GUI(s) via GUIDE via programming Program GUI(s) Initialization Actions Coordination Data management Shutdown Test GUI(s) Unusual inputs De
1 About GUIs in MATLAB® Software Ways to Build MATLAB GUIs A MATLAB GUI is a figure window to which you add user-operated controls. You can select, size, and position these components as you like. Using callbacks you can make the components do what you want when the user clicks or manipulates them with keystrokes. You can build MATLAB GUIs in two ways: • Use GUIDE (GUI Development Environment), an interactive GUI construction kit.
Ways to Build MATLAB® GUIs Type of GUI Technique Dialog box MATLAB software provides a selection of standard dialog boxes that you can create with a single function call. For an example, see the documentation for msgbox, which also provides links to functions that create specialized predefined dialog boxes. GUI containing just a few components It is often simpler to create GUIs that contain only a few components programmatically. You can fully define each component with a single function call.
1 1-10 About GUIs in MATLAB® Software
2 How to Create a GUI with GUIDE • “Introduction to GUIDE” on page 2-2 • “About the Simple GUIDE GUI Example” on page 2-9 • “Lay Out the Simple GUI in GUIDE” on page 2-11 • “Save the GUI Layout” on page 2-25 • “Program the Simple GUIDE GUI” on page 2-28 • “Use the Completed Simple GUIDE GUI” on page 2-36
2 How to Create a GUI with GUIDE Introduction to GUIDE In this section... “What Is GUIDE?” on page 2-2 “Opening GUIDE” on page 2-2 “Getting Help in GUIDE” on page 2-4 “Laying Out a GUIDE GUI” on page 2-7 “Programming a GUIDE GUI” on page 2-8 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 laying out and programming GUIs.
Introduction to GUIDE When you right-click a FIG-file in this way, the figure opens in the GUIDE Layout Editor, where you can work on it.
2 How to Create a GUI with GUIDE All tools in the tool palette have tool tips. Setting a GUIDE preference lets you display the palette in GUIDE with tool names or just their icons. See “GUIDE Preferences” on page 5-2 for more information. Getting Help in GUIDE When you open GUIDE to create a new GUI, a gridded layout area displays. It has a menu bar and toolbar above it, a tool palette to its left, and a status bar below it, as shown below. See “GUIDE Tools Summary” on page 4-3 for a full description.
Introduction to GUIDE The first three options lead you to topics in the GUIDE documentation that can help you get started using GUIDE. The Example GUIs option opens a list of complete examples of GUIs built using GUIDE that you can browse, study, open in GUIDE, and run. The bottom option, Online Video Demos, opens a list of GUIDE- and related GUI-building video tutorials on MATLAB Central. You can access MATLAB video demos, as well as the page on MATLAB Central by clicking links in the following table.
2 How to Create a GUI with GUIDE Type of Video Video Content MATLAB New Feature Demos New Graphics and GUI Building Features in Version 7.6 (9 min, 31 s) New Graphics and GUI Building Features in Version 7.5 (2 min, 47 s) New Creating Graphical User Interfaces features in Version 7 (4 min, 24 s) MATLAB Central Video Tutorials Archive for the “GUI or GUIDE” Category from 2005 to present.
Introduction to GUIDE Authors add new tutorials to the set over time. Bookmark this page and revisit it occasionally to see them. Laying Out a GUIDE GUI The GUIDE Layout Editor enables you to populate a GUI by clicking and dragging GUI components into the layout area. There you can resize, group and align buttons, text fields, sliders, axes, and other components you add.
2 How to Create a GUI with GUIDE • Create menus and context menus • Create toolbars • Modify the appearance of components • Set tab order • View a hierarchical list of the component objects • Set GUI options The following topic, “Lay Out the Simple GUI in GUIDE” on page 2-11, uses some of these tools to show you the basics of laying out a GUI. “GUIDE Tools Summary” on page 4-3 describes the tools.
About the Simple GUIDE GUI Example About the Simple GUIDE GUI Example In this section... “Simple GUIDE GUI Components” on page 2-9 “View Simple GUIDE GUI Layout and Code File” on page 2-10 Simple GUIDE GUI Components This section shows you how to use GUIDE to create the graphical user interface (GUI) shown in the following figure.
2 How to Create a GUI with GUIDE To use the GUI, select a data set from the pop-up menu, then click one of the plot-type buttons. Clicking the button triggers the execution of a callback that plots the selected data in the axes. Subsequent topics, starting with “Lay Out the Simple GUI in GUIDE” on page 2-11, guide you through the steps to create this GUI. We recommend that you create the GUI for yourself as the best way to learn how to use GUIDE.
Lay Out the Simple GUI in GUIDE Lay Out the Simple GUI in GUIDE In this section... “Open a New GUI in the GUIDE Layout Editor” on page 2-11 “Set the GUI Figure Size in GUIDE” on page 2-14 “Add Components to the Simple GUIDE GUI” on page 2-15 Open a New GUI in the GUIDE Layout Editor 1 Start GUIDE by typing guide at the MATLAB prompt. The GUIDE Quick Start dialog displays, as shown in the following figure.
2 How to Create a GUI with GUIDE 2 In the GUIDE Quick Start dialog box, select the Blank GUI (Default) template. Click OK to display the blank GUI in the Layout Editor, as shown in the following figure.
Lay Out the Simple GUI in GUIDE 3 Display the names of the GUI components in the component palette. Select File > Preferences. Then select GUIDE > Show names in component palette, and then click OK. The Layout Editor then appears as shown in the following figure.
2 How to Create a GUI with GUIDE Set the GUI Figure Size in GUIDE Set the size of the GUI by resizing the grid area in the Layout Editor. Click the lower-right corner and drag it until the GUI is approximately 3 in. high and 4 in. wide. If necessary, make the window larger.
Lay Out the Simple GUI in GUIDE Add Components to the Simple GUIDE GUI 1 Add the three push buttons to the GUI. Select the push button tool from the component palette at the left side of the Layout Editor and drag it into the layout area. Create three buttons this way, positioning them approximately as shown in the following figure. 2 Add the remaining components to the GUI.
2 How to Create a GUI with GUIDE Arrange the components as shown in the following figure. Resize the axes component to approximately 2-by-2 inches. Align the Components If several components have the same parent, you can use the Alignment Tool to align them to one another. To align the three push buttons: 1 Select all three push buttons by pressing Ctrl and clicking them. 2 Select Tools > Align Objects.
Lay Out the Simple GUI in GUIDE 3 Make these settings in the Alignment Tool, as shown in the following figure: • Left-aligned in the horizontal direction. • 20 pixels spacing between push buttons in the vertical direction.
2 How to Create a GUI with GUIDE 4 Click OK. Your GUI now looks like this in the Layout Editor. Add Text to the Components The push buttons, pop-up menu, and static text have default labels when you create them. Their text is generic, for example Push Button 1. Change the text to be specific to your GUI, so that it explains what the component is for. This topic shows you how to modify the default text.
Lay Out the Simple GUI in GUIDE After you have added the appropriate text, the GUI will look like this in the Layout Editor. Label the Push Buttons. Each of the three push buttons lets the GUI user choose a plot type: surf, mesh, and contour. This topic shows you how to label the buttons with those choices. 1 Select Property Inspector from the View menu.
2 How to Create a GUI with GUIDE 2 In the layout area, select the top push button by clicking it. 3 In the Property Inspector, select the String property and then replace the existing value with the word Surf. 4 Click outside the String field. The push button label changes to Surf.
Lay Out the Simple GUI in GUIDE 5 Select each of the remaining push buttons in turn and repeat steps 3 and 4. Label the middle push button Mesh, and the bottom button Contour. List Pop-Up Menu Items. The pop-up menu provides a choice of three data sets: peaks, membrane, and sinc. These data sets correspond to MATLAB functions of the same name. This topic shows you how to list those data sets as choices in the pop-menu. 1 In the layout area, select the pop-up menu by clicking it.
2 How to Create a GUI with GUIDE 3 Replace the existing text with the names of the three data sets: Peaks, Membrane, and Sinc. Press Enter to move to the next line. 4 When you have finished editing the items, click OK. The first item in your list, Peaks, appears in the pop-up menu in the layout area. Modify the Static Text. In this GUI, the static text serves as a label for the pop-up menu. The user cannot change this text. This topic shows you how to change the static text to read Select Data.
Lay Out the Simple GUI in GUIDE 3 Click OK. The phrase Select Data appears in the static text component above the pop-up menu. Completed Simple GUIDE GUI Layout In the Layout Editor, your GUI now looks like this and the next step is to save the layout. The next topic, “Save the GUI Layout” on page 2-25, tells you how to save it.
2 2-24 How to Create a GUI with GUIDE
Save the GUI Layout Save the GUI Layout When you save a GUI, GUIDE creates two files, a FIG-file and a code file. The FIG-file, with extension .fig, is a binary file that contains a description of the layout. The code file, with extension .m, contains MATLAB functions that control the GUI. 1 Save and activate your GUI by selecting Run from the Tools menu. 2 GUIDE displays the following dialog box. Click Yes to continue.
2 How to Create a GUI with GUIDE 4 Browse to any folder for which you have write privileges, and then enter the filename simple_gui for the FIG-file. GUIDE saves both the FIG-file and the code file using this name. 5 If the folder in which you save the GUI is not on the MATLAB path, GUIDE opens a dialog box, giving you the option of changing the current folder to the folder containing the GUI files, or adding that folder to the top or bottom of the MATLAB path. 6 GUIDE saves the files simple_gui.
Save the GUI Layout To run a GUI created with GUIDE without opening GUIDE, execute its code file by typing its name. simple_gui You can also use the run command with the code file, for example, run simple_gui Note Do not attempt to run a GUIDE GUI by opening its FIG-file outside of GUIDE. If you do so, the figure opens and appears ready to use, but the GUI does not initialize and its callbacks do not function.
2 How to Create a GUI with GUIDE Program the Simple GUIDE GUI In this section... “Add Code to the Simple GUIDE GUI” on page 2-28 “Generate Data to Plot” on page 2-28 “Program the Pop-Up Menu” on page 2-31 “Program the Push Buttons” on page 2-33 Add Code to the Simple GUIDE GUI When you saved your GUI in the previous topic, “Save the GUI Layout” on page 2-25, GUIDE created two files: a FIG-file simple_gui.fig that contains the GUI layout and a file, simple_gui.
Program the Simple GUIDE GUI The cursor moves to the opening function, which already contains this code: % --- Executes just before simple_gui is made visible. function simple_gui_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn.
2 How to Create a GUI with GUIDE % uiwait(handles.figure1); 2 Create data for the GUI to plot by adding the following code to the opening function immediately after the comment that begins % varargin... % 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; % Set the current data value. handles.current_data = handles.peaks; surf(handles.
Program the Simple GUIDE GUI Program the Pop-Up Menu The pop-up menu enables the user to select the data to plot. When the GUI user selects one of the three plots, MATLAB software sets the pop-up menu Value property to the index of the selected string. The pop-up menu callback reads the pop-up menu Value property to determine the item that the menu currently displays , and sets handles.current_data accordingly. 1 Display the pop-up menu callback in the MATLAB Editor.
2 How to Create a GUI with GUIDE If the editor is not already open, GUIDE opens it to display the GUI code file, and the cursor moves to the pop-menu callback, which already contains this code: % --- Executes on selection change in popupmenu1.
Program the Simple GUIDE GUI It then uses a switch statement to make the selected data set the current data. The last statement saves the changes to the handles structure. % Determine the selected data set. str = get(hObject, 'String'); val = get(hObject,'Value'); % Set current data to the selected data set. switch str{val}; case 'Peaks' % User selects peaks. handles.current_data = handles.peaks; case 'Membrane' % User selects membrane. handles.current_data = handles.
2 How to Create a GUI with GUIDE 1 Display the Surf push button callback in the MATLAB Editor. Right-click the Surf push button in the Layout Editor to display a context menu. From that menu, select View Callbacks > Callback. In the editor, the cursor moves to the Surf push button callback in the GUI code file, which already contains this code: % --- Executes on button press in pushbutton1.
Program the Simple GUIDE GUI 3 Repeat steps 1 and 2 to add similar code to the Mesh and Contour push button callbacks. • Add this code to the Mesh push button callback, pushbutton2_Callback: % Display mesh plot of the currently selected data. mesh(handles.current_data); • Add this code to the Contour push button callback, pushbutton3_Callback: % Display contour plot of the currently selected data. contour(handles.current_data); 4 Save your code by selecting Save from the File menu.
2 How to Create a GUI with GUIDE Use the Completed Simple GUIDE GUI Open and Run the GUI In “Program the Simple GUIDE GUI” on page 2-28, you programmed the pop-up menu and the push buttons. You also created data for them to use and initialized the display. Now you can run your GUI and see how it works. 1 Run your GUI by selecting Run from the Layout Editor Tools menu. If the GUI is on your MATLAB path or in your current folder, you can also run it by typing its name, simple_gui, at the prompt.
Use the Completed Simple GUIDE GUI give a GUI docking controls, but it must display a menu bar or a toolbar to enable them. For more information, see “How Menus Affect Figure Docking” on page 6-103. 2 In the pop-up menu, select Membrane, then click the Mesh button. The GUI displays a mesh plot of the MathWorks® L-shaped Membrane logo. 3 Try other combinations before closing the GUI.
2 2-38 How to Create a GUI with GUIDE
3 How to Create a Simple GUI Programmatically • “About the Simple Programmatic GUI Example” on page 3-2 • “Create the Simple Programmatic GUI Code File” on page 3-5 • “Lay Out the Simple Programmatic GUI” on page 3-7 • “Code the Simple Programmatic GUI” on page 3-11 • “Use the Completed Simple Programmatic GUI” on page 3-20
3 How to Create a Simple GUI Programmatically About the Simple Programmatic GUI Example Simple Programmatic GUI Components This section shows you how to write MATLAB code that creates the example graphical user interface (GUI) shown in the following figure.
About the Simple Programmatic GUI Example The next topic, “Functions for the Simple Programmatic GUI” on page 3-3, summarizes the functions used to create this example GUI. Subsequent topics guide you through the process of creating the GUI. This process begins with “Create the Simple Programmatic GUI Code File” on page 3-5. We recommend that you create the GUI for yourself.
3 How to Create a Simple GUI Programmatically MATLAB Functions Used to Create the Simple Programmatic GUI (Continued) Function Description movegui Move GUI figure to specified location on screen. uicontrol Create user interface control objects, such as push buttons, static text, and pop-up menus.
Create the Simple Programmatic GUI Code File Create the Simple Programmatic GUI Code File Start by creating a file for the example GUI. Because the file will contain functions, it is a function file as opposed to a script file, which contains a sequence of MATLAB commands but does not define functions. 1 At the MATLAB prompt, type edit. MATLAB opens a blank document in the Editor. 2 Type or copy the following statement into the editor. This function statement is the first line in the file.
3 How to Create a Simple GUI Programmatically The next section, “Lay Out the Simple Programmatic GUI” on page 3-7, shows you how to add components to your GUI.
Lay Out the Simple Programmatic GUI Lay Out the Simple Programmatic GUI In this section... “Create a Figure for a Programmatic GUI” on page 3-7 “Add Components to a Programmatic GUI” on page 3-7 Create a Figure for a Programmatic GUI In MATLAB software, a GUI is a figure. This first step creates the figure and positions it on the screen. It also makes the GUI invisible so that the GUI user cannot see the components being added or initialized.
3 How to Create a Simple GUI Programmatically hcontour = uicontrol('Style','pushbutton',... 'String','Countour','Position',[315,135,70,25]); These statements use the uicontrol function to create the push buttons. Each statement uses a series of property/value pairs to define a push button. Property Description Style In the example, pushbutton specifies the component as a push button. String Specifies the label that appears on each push button.
Lay Out the Simple Programmatic GUI 4 Align all components except the axes along their centers with the following statement. Add it to the code file following all the component definitions. align([hsurf,hmesh,hcontour,htext,hpopup],'Center','None'); 5 Make your GUI visible by adding this command following the align command.
3 How to Create a Simple GUI Programmatically 7 Run your code by typing simple_gui2 at the command line. This is what your GUI now looks like. Note that you can select a data set in the pop-up menu and click the push buttons. But nothing happens. This is because there is no code in the file to service the pop-up menu or the buttons. 8 Type help simple_gui2 at the command line. MATLAB software displays this help text.
Code the Simple Programmatic GUI Code the Simple Programmatic GUI In this section... “Program the Pop-Up Menu” on page 3-11 “Program the Push Buttons” on page 3-12 “Program Callbacks for the Simple GUI Components” on page 3-12 “Initialize the Simple Programmatic GUI” on page 3-13 “The Completed Simple Programmatic GUI Code File” on page 3-16 Program the Pop-Up Menu The pop-up menu enables users to select the data to plot.
3 How to Create a Simple GUI Programmatically end The next topic, “Program the Push Buttons” on page 3-12, shows you how to write callbacks for the three push buttons. Program the Push Buttons Each of the three push buttons creates a different type of plot using the data specified by the current selection in the pop-up menu. The push button callbacks plot the data in current_data. They automatically have access to current_data because they are nested at a lower level.
Code the Simple Programmatic GUI that particular event. But how does the software know which callback to execute? You must use each component’s Callback property to specify the name of the callback with which it is associated. 1 To the uicontrol statement that defines the Surf push button, add the property/value pair 'Callback',{@surfbutton_Callback} so that the statement looks like this: hsurf = uicontrol('Style','pushbutton','String','Surf',... 'Position',[315,220,70,25],...
3 How to Create a Simple GUI Programmatically resize when the GUI is resized. Normalized units map the lower-left corner of the figure window to (0,0) and the upper-right corner to (1.0, 1.0). • Generate the data to plot. The example needs three sets of data: peaks_data, membrane_data, and sinc_data. Each set corresponds to one of the items in the pop-up menu.
Code the Simple Programmatic GUI function simple_gui2 % SIMPLE_GUI2 Select a data set from the pop-up menu, then % click one of the plot-type push buttons. Clicking the button % plots the selected data in the axes. % Create and hide the GUI figure as it is being constructed. f = figure('Visible','off','Position',[360,500,450,285]); % Construct the components hsurf = uicontrol('Style','pushbutton','String','Surf',... 'Position',[315,220,70,25]); hmesh = uicontrol('Style','pushbutton','String','Mesh',...
3 How to Create a Simple GUI Programmatically set(f,'Name','Simple GUI') % Move the GUI to the center of the screen. movegui(f,'center') % Make the GUI visible. set(f,'Visible','on'); end 3 Run your code by typing simple_gui2 at the command line. The initialization above cause it to display the default peaks data with the surf function, making the GUI look like this.
Code the Simple Programmatic GUI % Create and then hide the GUI as it is being constructed. f = figure('Visible','off','Position',[360,500,450,285]); % Construct the components. hsurf = uicontrol('Style','pushbutton','String','Surf',... 'Position',[315,220,70,25],... 'Callback',{@surfbutton_Callback}); hmesh = uicontrol('Style','pushbutton','String','Mesh',... 'Position',[315,180,70,25],... 'Callback',{@meshbutton_Callback}); hcontour = uicontrol('Style','pushbutton',... 'String','Countour',...
3 How to Create a Simple GUI Programmatically set(f,'Name','Simple GUI') % Move the GUI to the center of the screen. movegui(f,'center') % Make the GUI visible. set(f,'Visible','on'); % % % Callbacks for simple_gui2. These callbacks automatically have access to component handles and initialized data because they are nested at a lower level. % % % Pop-up menu callback. Read the pop-up menu Value property to determine which item is currently displayed and make it the current data.
Code the Simple Programmatic GUI function contourbutton_Callback(source,eventdata) % Display contour plot of the currently selected data. contour(current_data); end end The next topic, “Use the Completed Simple Programmatic GUI” on page 3-20, shows the final code file and runs the GUI.
3 How to Create a Simple GUI Programmatically Use the Completed Simple Programmatic GUI Open and Run the GUI 1 Run the GUI by typing the name of the code file at the command line. simple_gui2 2 In the pop-up menu, select Membrane, and then click the Mesh button. The GUI displays a mesh plot of the MATLAB logo.
Use the Completed Simple Programmatic GUI 3 Try other combinations before closing the GUI.
3 3-22 How to Create a Simple GUI Programmatically
Create GUIs with GUIDE Chapter 4, What Is GUIDE? (p. 4-1) Introduces GUIDE Chapter 5, GUIDE Preferences and Options (p. 5-1) Describes briefly the available MATLAB preferences and GUI options. Chapter 6, Lay Out a GUIDE GUI (p. 6-1) Shows you how to start GUIDE and from there how to populate the GUI and create menus. Provides guidance in designing a GUI for cross-platform compatibility. Chapter 7, Save and Run a GUIDE GUI (p. 7-1) Describes the files used to store the GUI.
4 What Is GUIDE? • “GUIDE: Getting Started” on page 4-2 • “GUIDE Tools Summary” on page 4-3
4 What Is GUIDE? GUIDE: Getting Started In this section... “GUI Layout” on page 4-2 “GUI Programming” on page 4-2 GUI Layout GUIDE, the MATLAB graphical user interface development environment, provides a set of tools for creating graphical user interfaces (GUIs). These tools simplify the process of laying out and programming GUIs.
GUIDE Tools Summary GUIDE Tools Summary The GUIDE tools are available from the Layout Editor shown in the figure below. The tools are called out in the figure and described briefly below. Subsequent sections show you how to use them.
4 What Is GUIDE? Use This Tool... 4-4 To... Layout Editor Select components from the component palette, at the left side of the Layout Editor, and arrange them in the layout area. See “Add Components to the GUI” on page 6-19 for more information. Figure Resize Tab Set the size at which the GUI is initially displayed when you run it. See “Set the GUI Size” on page 6-15 for more information. Menu Editor Create menus and context, i.e., pop-up, menus.
GUIDE Tools Summary Use This Tool... To... Editor Display, in your default editor, the code file associated with the GUI. See “Files Generated by GUIDE” on page 8-7 for more information.
4 4-6 What Is GUIDE?
5 GUIDE Preferences and Options • “GUIDE Preferences” on page 5-2 • “GUI Options” on page 5-9
5 GUIDE Preferences and Options GUIDE Preferences In this section... “Set Preferences” on page 5-2 “Confirmation Preferences” on page 5-2 “Backward Compatibility Preference” on page 5-4 “All Other Preferences” on page 5-6 Set Preferences You can set preferences for GUIDE by selecting Preferences from the File menu. These preferences apply to GUIDE and to all GUIs you create.
GUIDE Preferences In the Preferences dialog box, click General > Confirmation Dialogs to access the GUIDE confirmation preferences. Look for the word GUIDE in the Tool column. Prompt to Save on Activate When you activate a GUI by clicking the Run button in the Layout Editor, a dialog box informs you of the impending save and lets you choose whether or not you want to continue.
5 GUIDE Preferences and Options Prompt to Save on Export When you select Export from the Layout Editor File menu, a dialog box informs you of the impending save and lets you choose whether or not you want to continue. For more information on exporting a GUI, see “Export a GUIDE GUI to a Code File” on page 7-9. Backward Compatibility Preference MATLAB Version 5 or Later Compatibility GUI FIG-files created or modified with MATLAB 7.
GUIDE Preferences To make a FIG-file backward compatible, select File > Preferences > General > MAT-Files, and then select MATLAB Version 5 or later (save -v6). Note The -v6 option discussed in this section is obsolete and will be removed in a future version of MATLAB.
5 GUIDE Preferences and Options All Other Preferences GUIDE provides other preferences, for the Layout Editor interface and for inserting code comments. In the Preferences dialog box, click GUIDE to access these preferences.
GUIDE Preferences • “Add Comments for Newly Generated Callback Functions” on page 5-8 Show Names in Component Palette Displays both icons and names in the component palette, as shown below. When unchecked, the icons alone are displayed in two columns, with tooltips. Show File Extension in Window Title Displays the GUI FIG-file filename with its file extension, .fig, in the Layout Editor window title. If unchecked, only the filename is displayed.
5 GUIDE Preferences and Options Add Comments for Newly Generated Callback Functions Callbacks are blocks of code that execute in response to actions by the GUI’s user, such as clicking buttons or manipulating sliders. By default, GUIDE sets up templates that declare callbacks as functions and adds comments at the beginning of each one. Most of the comments are similar to the following. % --- Executes during object deletion, before destroying properties.
GUI Options GUI Options In this section... “The GUI Options Dialog Box” on page 5-9 “Resize Behavior” on page 5-10 “Command-Line Accessibility” on page 5-11 “Generate FIG-File and MATLAB File” on page 5-12 “Generate FIG-File Only” on page 5-14 The GUI Options Dialog Box You can use the GUI Options dialog box to configure various behaviors that are specific to the GUI you are creating. These options take effect when you next save the GUI.
5 GUIDE Preferences and Options The following sections describe the options in this dialog box: Resize Behavior You can control whether users can resize the figure window containing your GUI and how MATLAB software handles resizing. GUIDE provides three options: • Non-resizable — Users cannot change the window size (default). • Proportional — The software automatically rescales the components in the GUI in proportion to the new figure window size.
GUI Options see the GUIDE examples “Panel” on page 8-38 and “An Address Book Reader (GUIDE)” on page 10-81. Also see the example “Using Panel Containers in Figures — Uipanels”, which does not use GUIDE. Command-Line Accessibility You can restrict access to a GUI figure from the command line or from a code file with the GUIDE Command-line accessibility options.
5 GUIDE Preferences and Options Option Description Callback (GUI becomes Current Figure within Callbacks) The GUI can be accessed only from within a GUI callback. The GUI cannot be accessed from the command line or from a script. This is the default. Off (GUI never becomes Current Figure) The GUI can not be accessed from a callback, the command line, or a script, without the handle.
GUI Options GUIDE also adds a callback whenever you edit a callback routine from the Layout Editor’s right-click context menu and when you add menus to the GUI using the Menu Editor. See “Customizing Callbacks in GUIDE” on page 8-15 for general information about callbacks. Note This option is available only if you first select the Generate FIG-file and MATLAB file option.
5 GUIDE Preferences and Options Use System Color Scheme for Background The default color used for GUI components is system dependent. This option enables you to make the figure background color the same as the default component background color. 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 and without system color matching.
GUI Options limited editing capability and may be useful for GUIs generated in MATLAB Versions 5.3 and earlier. See the guide function for more information. GUIDE selects Generate FIG-file only as the default if you do one of the following: • Start GUIDE from the command line by providing one or more figure handles as arguments. guide(fh) In this case, GUIDE selects Generate FIG-file only, even when a code file with a corresponding name exists in the same folder.
5 GUIDE Preferences and Options arguments to that function. For example, setting the Callback property of a push button to sqrt(2) causes the result of the expression to display in the Command Window: ans = 1.4142 Any file that a callback executes must be in the current folder or on the MATLAB path.
6 Lay Out a GUIDE GUI • “Design a GUI” on page 6-2 • “Start GUIDE” on page 6-4 • “Select a GUI Template” on page 6-6 • “Set the GUI Size” on page 6-15 • “Add Components to the GUI” on page 6-19 • “Align Components” on page 6-89 • “Set Tab Order” on page 6-98 • “Create Menus in a GUIDE GUI” on page 6-101 • “Create Toolbars” on page 6-122 • “View the Object Hierarchy” on page 6-136 • “Designing for Cross-Platform Compatibility” on page 6-137
6 Lay Out a GUIDE GUI Design a GUI Before creating the actual GUI, it is important to decide what it is you want your GUI to do and how you want it to work. It is helpful to draw your GUI on paper and envision what the user sees and what actions the user takes. Note MATLAB software provides a selection of standard dialog boxes that you can create with a single function call.
Design a GUI • AskTog — Essays on good design and a list of First Principles for good user interface design. The author, Bruce Tognazzini, is a well-respected user interface designer. http://www.asktog.com/basics/firstPrinciples.html. • Galitz, Wilbert, O., Essential Guide to User Interface Design. Wiley, New York, NY, 2002. • GUI Design Handbook — A detailed guide to the use of GUI controls. http://www.fast-consulting.com/desktop.htm. • Johnson, J.
6 Lay Out a GUIDE GUI Start GUIDE There are many ways to start GUIDE. You can start GUIDE from the: • Command line by typing guide • Start menu by selecting MATLAB > GUIDE (GUI Builder) • MATLAB File menu by selecting New > GUI • MATLAB toolbar by clicking the GUIDE button However you start GUIDE, it displays the GUIDE Quick Start dialog box shown in the following figure.
Start GUIDE • Open Existing GUI — Enables you to open an existing GUI in GUIDE. You can choose a GUI from your current folder or browse other directories.
6 Lay Out a GUIDE GUI Select a GUI Template In this section... “Access the Templates” on page 6-6 “Template Descriptions” on page 6-7 Access the Templates GUIDE provides several templates that you can modify to create your own GUIs. The templates are fully functional GUIs; they are already programmed. You can access the templates in two ways: • Start GUIDE. See “Start GUIDE” on page 6-4 for information. • If GUIDE is already open, select New from the File menu in the Layout Editor.
Select a GUI Template To use a template: 1 Select a template in the left pane. A preview displays in the right pane. 2 Optionally, name your GUI now by selecting Save new figure as and typing the name in the field to the right. GUIDE saves the GUI before opening it in the Layout Editor. If you choose not to name the GUI at this point, GUIDE prompts you to save it and give it a name the first time you run the GUI. 3 Click OK to open the GUI template in the Layout Editor.
6 Lay Out a GUIDE GUI Blank GUI The blank GUI template displayed in the Layout Editor is shown in the following figure. 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.
Select a GUI Template GUI with Uicontrols The following figure shows the template for a GUI with user interface controls (uicontrols) displayed in the Layout Editor. User interface controls include push buttons, sliders, radio buttons, check boxes, editable and static text components, list boxes, and toggle buttons.
6 Lay Out a GUIDE GUI When you run the GUI by clicking the Run button , the GUI appears as shown in the following figure. 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). To view the code for these user interface controls, open the template in the Layout Editor and click the Editor button on the toolbar.
Select a GUI Template When you run the GUI by clicking the Run button on the toolbar, the GUI displays a plot of five lines, each of which is generated from random numbers using the MATLAB rand(5) command. The following figure shows an example.
6 Lay Out a GUIDE GUI 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: • Open displays a dialog box from which you can open files on your computer. • Print opens the Print dialog box. Clicking OK in the Print dialog box prints the figure. • Close closes the GUI. To view the code for these menu choices, open the template in the Layout Editor and click the Editor button on the toolbar.
Select a GUI Template Modal Question Dialog The modal question dialog template displayed in the Layout Editor is shown in the following figure.
6 Lay Out a GUIDE GUI The GUI returns the text string Yes or No, depending on which button you click. Select this template if you want your GUI to return a string or to be modall. Modal GUIs are blocking, which means that the current code file stops executing until the GUI restores execution; this means that the user cannot interact with other MATLAB windows until one of the buttons is clicked. Note Modal dialog boxes (figures with WindowStyle set to 'modal') cannot display menus or toolbars.
Set the GUI Size Set the GUI Size Set the size of the GUI by resizing the grid area in the Layout Editor. Click the lower-right corner and drag it until the GUI is the desired size. If necessary, make the window larger. Click and drag corner to resize As you drag the corner handle, the readout in the lower right corner shows the current position of the GUI in pixels.
6 Lay Out a GUIDE GUI Note Many of the following steps show you how to use the Property Inspector to set properties of a GUI and its components. If you are not familiar with using this tool and its context-sensitive help, see “Property Inspector” on page 6-92 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 or click the Property Inspector button .
Set the GUI Size 4 Type the x and y coordinates of the point where you want the lower-left corner of the GUI to appear, and its width and height. 5 Reset the Units property to its previous setting, either characters or normalized. Note Setting the Units property to characters (nonresizable GUIs) or normalized (resizable GUIs) gives the GUI a more consistent appearance across platforms. See “Cross-Platform Compatible Units” on page 6-139 for more information.
6 Lay Out a GUIDE GUI Maximize the Layout Area You can make maximum use of space within the Layout Editor by hiding the GUIDE toolbar, status bar, or both. To do this, deselect Show Toolbar and/or Show Status Bar from the View menu. Showing only tool icons on the component palette gives you more room as well. To show only tool icons on the component palette, select Preferences from the GUIDE File menu and deselect Show names in component palette.
Add Components to the GUI Add Components to the GUI In this section...
6 Lay Out a GUIDE GUI Available Components The component palette at the left side of the Layout Editor contains the components that you can add to your GUI. You can display it with or without names. When you first open the Layout Editor, the component palette contains only icons. To display the names of the GUI components, select Preferences from the File menu, check the box next to Show names in component palette, and click OK.
Add Components to the GUI Component Icon Description Push Button Push buttons generate an action when clicked. For example, an OK button might apply settings and close a dialog box. When you click a push button, it appears depressed; when you release the mouse button, the push button appears raised. Slider Sliders accept numeric input within a specified range by enabling the user to move a sliding bar, which is called a slider or thumb.
6 Lay Out a GUIDE GUI Component Icon Description Pop-Up Menu Pop-up menus open to display a list of choices when users click the arrow. List Box List boxes display a list of items and enable users to select one or more items. Toggle Button Toggle buttons generate an action and indicate whether they are turned on or off. When you click a toggle button, it appears depressed, showing that it is on.
Add Components to the GUI Component Icon Description Button Group Button groups are like panels but are used to manage exclusive selection behavior for radio buttons and toggle buttons. Toolbar You can create toolbars containing push buttons and toggle buttons. Use the GUIDE Toolbar Editor to create toolbar buttons. Choose between predefined buttons, such as Save and Print, and buttons which you customize with your own icons and callbacks.
6 Lay Out a GUIDE GUI • Click here to display the controlsuite GUI in the GUIDE Layout Editor. • Click here to display the controlsuite GUI code file in the MATLAB Editor. • Click here to run the controlsuite GUI. Note If you want to experiment with the controlsuite GUI, first save a copy of the FIG-file and the code file in a writable folder on your MATLAB path and work with those copies. When you open controlsuite.fig in GUIDE, it looks like this in the Layout Editor.
Add Components to the GUI The GUI contains 15 controls organized within seven panels. The Action Panel contains a static text component that changes to describe the actions a user makes when manipulating the controls. For example, selecting Charlie in the Listbox panel places the word Charlie in the Action Panel.
6 Lay Out a GUIDE GUI Run the controlsuite GUI When you click the Run Figure button in the Layout Editor, the GUI opens, initializes, and displays itself as shown in the following figure. The following sections describe several controls and the code they execute (their callbacks). Study the sections of code and click the links to the callbacks below to learn the how functions in the controlsuite code file control the GUI. The Push Button.
Add Components to the GUI The code that generates the message is part of the pushbutton1_Callback, shown below: function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.textStatus, 'String', 'Push button pushed') This callback is activated when pushbutton1 is clicked.
6 Lay Out a GUIDE GUI % hObject % eventdata % handles handle to togglebutton1 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of togglebutton1 isDown = get(hObject,'Value'); if isDown set(handles.textStatus, 'string', 'Toggle down') else set(handles.
Add Components to the GUI The popup’s callback controls its behavior. GUIDE generates this much of the callback.
6 Lay Out a GUIDE GUI retrieve the name of the colormap That name, selectedText, is composed into a message and placed in the textStatus static text field, and used by the colormap function to reset the colormap. For example, if the user selects autumn from the popup, the surface changes to shades of yellow, orange, and red, as shown in the following cutout from the GUI. The slider control sets the viewing azimuth, causing the plot to rotate when the user moves its “thumb” or clicks its arrows.
Add Components to the GUI For another example describing how to couple uitables with graphics, see “GUI to Interactively Explore Data in a Table (GUIDE)” on page 10-31.
6 Lay Out a GUIDE GUI If You Are Adding... Then... Panels or button groups See “Add a Component to a Panel or Button Group” on page 6-34. Menus See “Create Menus in a GUIDE GUI” on page 6-101 Toolbars See “Create Toolbars” on page 6-122 ActiveX controls See “Add ActiveX Controls” on page 6-77. See “Grid and Rulers” on page 6-96 for information about using the grid. 2 Assign a unique identifier to each component. Do this by setting the value of the component Tag properties.
Add Components to the GUI This is an example of a GUI in the Layout Editor. Components in the Layout Editor are not active. Use Coordinates to Place Components The status bar at the bottom of the GUIDE Layout Editor displays: • Current Point — The current location of the mouse relative to the lower left corner of the grid area in the Layout Editor.
6 Lay Out a GUIDE GUI distances are relative to the parent figure, panel, or button group. All values are given in pixels. Rulers also display pixels. If you select a single component and move it, the first two elements of the position vector (distance from left, distance from bottom) are updated as you move the component. If you resize the component, the last two elements of the position vector (width, height) are updated as you change the size.
Add Components to the GUI GUIDE highlights the potential parent as shown in the following figure. The highlight indicates that if you drop the component or click the cursor, the component will be a child of the highlighted panel, button group, or figure. Highlight Cursor Note Assign a unique identifier to each component in your panel or button group by setting the value of its Tag property. See “Assign an Identifier to Each Component” on page 6-37 for more information.
6 Lay Out a GUIDE GUI Include Existing Components in Panels and Button Groups. When you add a new component or drag an existing component to a panel or button group, it will become a member, or child, of the panel or button group automatically, whether fully or partially enclosed by it. However, if the component is not entirely contained in the panel or button group, it appears to be clipped in the Layout Editor.
Add Components to the GUI The panel highlights when you move a control, indicating it now contains the control. The Object Browser updates to confirm the relationship. If you now move the panel, its child controls move with it. Tip You need to move controls with the mouse to register them with the surrounding panel or button group, even if only by a pixel or two. Selecting them and using arrow keys to move them does not accomplish this. Use the Object Browser to verify that controls are properly nested.
6 Lay Out a GUIDE GUI 3 In the Property Inspector, select Tag and then replace the value with the string you want to use as the identifier. In the following figure, Tag is set to mybutton. Define User Interface Controls User interface controls include push buttons, toggle buttons, sliders, radio buttons, edit text controls, static text controls, pop-up menus, check boxes, and list boxes. To define user interface controls, you must set certain properties.
Add Components to the GUI • “Static Text” on page 6-48 • “Pop-Up Menu” on page 6-50 • “List Box” on page 6-52 • “Toggle Button” on page 6-54 Note See “Available Components” on page 6-20 for descriptions of these components. See “Add Code for Components in Callbacks” on page 8-30 for basic examples of programming these components. Commonly Used Properties The most commonly used properties needed to describe a user interface control are shown in the following table.
6 Lay Out a GUIDE GUI Property Value Description String String. Can also be a cell array or character array of strings. Component label. For list boxes and pop-up menus it is a list of the items. Units characters, centimeters, inches, normalized, pixels, points. Default is characters. Units of measurement used to interpret the Position property vector Value Scalar or vector Value of the component. Interpretation depends on the type of component.
Add Components to the GUI To display the & character in a label, use two & characters in the string. The words remove, default, and factory (case sensitive) are reserved. To use one of these as a label, prepend a backslash (\) to the string. For example, \remove yields remove. The push button accommodates only a single line of text. If you specify more than one line, only the first line is shown.
6 Lay Out a GUIDE GUI Note Create your own icon with the icon editor described in “Icon Editor” on page 15-63. See ind2rgb for information on converting a matrix X and corresponding colormap, i.e., an (X, MAP) image, to RGB (truecolor) format. Slider To create a slider as shown in this figure: • Specify the range of the slider by setting its Min property to the minimum value of the slider and its Max property to the maximum value. The Min property must be less than Max.
Add Components to the GUI clicking the trough moves the slider thumb. Setting it to 1 or higher causes the thumb to move to Max or Min when the trough is clicked. As major_step increases, the thumb grows longer. When major_step is 1, the thumb is half as long as the trough. When major_step is greater than 1, the thumb continues to grow, slowly approaching the full length of the trough.
6 Lay Out a GUIDE GUI • Specify the radio button label by setting the String property to the desired label, in this case, Indent nested functions. To display the & character in a label, use two & characters in the string. The words remove, default, and factory (case sensitive) are reserved. To use one of these as a label, prepend a backslash (\) to the string. For example, \remove yields remove. The radio button accommodates only a single line of text.
Add Components to the GUI • If you want to set the position or size of the component to an exact value, then modify its Position property. See “Locate and Move Components” on page 6-83 and “Resize Components” on page 6-86 for details. • To add an image to a radio button, assign the button’s CData property an m-by-n-by-3 array of RGB values that defines a truecolor image. You must do this programmatically in the opening function of the GUI code file.
6 Lay Out a GUIDE GUI To display the & character in a label, use two & characters in the string. The words remove, default, and factory (case sensitive) are reserved. To use one of these as a label, prepend a backslash (\) to the string. For example, \remove yields remove. The check box accommodates only a single line of text. If you specify a component width that is too small to accommodate the specified String, MATLAB software truncates the string with an ellipsis.
Add Components to the GUI • Specify the text to be displayed when the edit text component is created by setting the String property to the desired string, in this case, Enter your name here. To display the & character in a label, use two & characters in the string. The words remove, default, and factory (case sensitive) are reserved. To use one of these as a label, prepend a backslash (\) to the string. For example, \remove yields remove.
6 Lay Out a GUIDE GUI If Max-Min is less than or equal to 1, the edit text component admits only a single line of input. If you specify a component width that is too small to accommodate the specified string, MATLAB software displays only part of the string. The user can use the arrow keys to move the cursor through the entire string.
Add Components to the GUI • Specify the text that appears in the component by setting the component String property to the desired text, in this case Select a data set. To display the & character in a list item, use two & characters in the string. The words remove, default, and factory (case sensitive) are reserved. To use one of these as a label, prepend a backslash (\) to the string. For example, \remove yields remove.
6 Lay Out a GUIDE GUI “Edit Text” on page 6-46, and for a programmatic approach, the section “Setting Font Characteristics” on page 11-18. Pop-Up Menu To create a pop-up menu (also known as a drop-down menu or combo box) with items one, two, three, and four, as shown in this figure: • Specify the pop-up menu items to be displayed by setting the String property to the desired items. Click the button to the right of the property name to open the Property Inspector editor.
Add Components to the GUI To display the & character in a menu item, use two & characters in the string. The words remove, default, and factory (case sensitive) are reserved. To use one of these as a label, prepend a backslash (\) to the string. For example, \remove yields remove. If the width of the component is too small to accommodate one or more of the specified strings, MATLAB software truncates those strings with an ellipsis.
6 Lay Out a GUIDE GUI • If you want to set the position and size of the component to exact values, then modify its Position property. See “Locate and Move Components” on page 6-83 and “Resize Components” on page 6-86 for details. The height of a pop-up menu is determined by the font size. The height you set in the position vector is ignored. Note The pop-up menu does not provide for a label. Use a “Static Text” on page 6-48 component to label the pop-up menu.
Add Components to the GUI To display the & character in a label, use two & characters in the string. The words remove, default, and factory (case sensitive) are reserved. To use one of these as a label, prepend a backslash (\) to the string. For example, \remove yields remove. If the width of the component is too small to accommodate one or more of the specified strings, MATLAB software truncates those strings with an ellipsis.
6 Lay Out a GUIDE GUI - To select more than one item when the component is created, set Value to a vector of indices of the selected items. Value = [1,3] results in the following selection. To enable selection of more than one item, you must specify the Max and Min properties so that their difference is greater than 1. For example, Max = 2, Min = 0. Max default is 1, Min default is 0. - If you want no initial selection, set the Max and Min properties to enable multiple selection, i.e.
Add Components to the GUI • Specify the toggle button label by setting its String property to the desired label, in this case, Left/Right Tile. To display the & character in a label, use two & characters in the string. The words remove, default, and factory (case sensitive) are reserved. To use one of these as a label, prepend a backslash (\) to the string. For example, \remove yields remove. The toggle button accommodates only a single line of text.
6 Lay Out a GUIDE GUI software sets Value to Max, and to Min when the user deselects it. The following figure shows the toggle button in the depressed position. • If you want to set the position or size of the component to an exact value, then modify its Position property. See “Locate and Move Components” on page 6-83 and “Resize Components” on page 6-86 for details. • To add an image to a toggle button, assign the button’s CData property an m-by-n-by-3 array of RGB values that defines a truecolor image.
Add Components to the GUI 1 Use the Property Inspector to modify the appropriate properties. Open the Property Inspector by selecting Property Inspector from the View menu or by clicking the Property Inspector button . 2 In the layout area, select the component you are defining. Note See “Available Components” on page 6-20 for descriptions of these components. See “Add Code for Components in Callbacks” on page 8-30 for basic examples of programming these components.
6 Lay Out a GUIDE GUI Property Values Description TitlePosition lefttop, centertop, righttop, leftbottom, centerbottom, rightbottom. Default is lefttop. Location of title string in relation to the panel or button group. Units characters, centimeters, inches, normalized, pixels, points. Default is characters.
Add Components to the GUI • Specify the panel title by setting the Title property to the desired string, in this case My Panel. To display the & character in the title, use two & characters in the string. The words remove, default, and factory (case sensitive) are reserved. To use one of these as a label, prepend a backslash (\) to the string. For example, \remove yields remove.
6 Lay Out a GUIDE GUI • If you want to set the position or size of the panel to an exact value, then modify its Position property. See “Locate and Move Components” on page 6-83 and “Resize Components” on page 6-86 for details. Note For more information and additional tips and techniques, see “Add a Component to a Panel or Button Group” on page 6-34 and the uipanel documentation.
Add Components to the GUI To display the & character in the title, use two & characters in the string. The words remove, default, and factory (case sensitive) are reserved. To use one of these as a label, prepend a backslash (\) to the string. For example, \remove yields remove. • Specify the location of the button group title by selecting one of the available TitlePosition property values from the pop-up menu, in this case lefttop.
6 Lay Out a GUIDE GUI Note For more information and additional tips and techniques, see “Add a Component to a Panel or Button Group” on page 6-34 and the uibuttongroup documentation. Define Axes Axes enable your GUI to display graphics such as graphs and images using commands such as: plot, surf, line, bar, polar, pie, contour, and mesh. To define an axes, you must set certain properties. To do this: 1 Use the Property Inspector to modify the appropriate properties.
Add Components to the GUI Property Values Description NextPlot add, replace, replacechildren. Default is replace Specifies whether plotting adds graphics, replaces graphics and resets axes properties to default, or replaces graphics only. Position 4-element vector: [distance from left, distance from bottom, width, height]. Size of the component and its location relative to its parent. Units normalized, centimeters, characters, inches, pixels, points. Default is normalized.
6 Lay Out a GUIDE GUI • Allow for tick marks to be placed outside the box that appears in the Layout Editor. The axes above looks like this in the layout editor; placement allows space at the left and bottom of the axes for tick marks. Functions that draw in the axes update the tick marks appropriately.
Add Components to the GUI • Use the title, xlabel, ylabel, zlabel, and text functions in the GUI code file to label an axes component. For example, xlh = (axes_handle,'Years') labels the X-axis as Years. The handle of the X-axis label is xlh. See “Customizing Callbacks in GUIDE” on page 8-15 for information about determining the axes handle. The words remove, default, and factory (case sensitive) are reserved. To use one of these in component text, prepend a backslash (\) to the string.
6 Lay Out a GUIDE GUI • If you customize axes properties, some of them (or example, callbacks, font characteristics, and axis limits and ticks) may get reset to default every time you draw a graph into the axes when the NextPlot property has its default value of 'replace'. To keep customized properties as you want them, set NextPlot to 'replacechildren' in the Property Inspector, as shown here. Define Tables Tables enable you to display data in a two dimensional table.
Add Components to the GUI Group Property Values Description Column ColumnName 1-by-n cell array of strings | {’numbered’} | empty matrix ([]) The header label of the column.
6 Lay Out a GUIDE GUI Drag the table icon on to the Layout Editor and right click in the table. Select Table Property Editor from its pop-up context menu. You can also select Table Property Editor from the Tools menu when you select a table by itself.
Add Components to the GUI Use the Table Property Editor. When you open it this way, the Table Property Editor displays the Column pane. You can also open it from the Property Inspector by clicking one of its Table Property Editor icons , in which case the Table Property Editor opens to display the pane appropriate for the property you clicked. Clicking items in the list on the left hand side of the Table Property Editor changes the contents of the pane to the right .
6 Lay Out a GUIDE GUI Button Purpose Accelerator Keys Windows Macintosh Insert Inserts a new column or row definition entry below the current one Insert Insert Delete Deletes the current column or row definition entry (no undo) Ctrl+D Cmd+D Copy Inserts a Copy of the selected entry in a new row below it Moves selected entry up one row Ctrl+P Cmd+P Ctrl+ uparrow Cmd+ uparrow Moves selected entry down one row Cmd+ Ctrl+ downarrow downarrow Up Down Keyboard equivalents only operate when
Add Components to the GUI Select Show names entered below as the column headers and set the ColumnName by entering Rate, Amount, Available, and Fixed/Adj in Name group. for the Available and Fixed/Adj columns set the ColumnEditable property to on.
6 Lay Out a GUIDE GUI For the Rate column, select Numeric. For the Amount Column select Custom and in the Custom Format Editor, choose Bank.
Add Components to the GUI Leave the Available column at the default value. This allows MATLAB to chose based on the value of the Data property of the table. For the Fixed/Adj column select Choice List to create a pop-up menu. In the Choice List Editor, click Insert to add a second choice and type Fixed and Adjustable as the 2 choices.
6 Lay Out a GUIDE GUI Note The In order for a user to select items from a choice list, the ColumnEditable property of the column the list occupies must be set to 'true'. The pop-up control only appears when the column is editable. Set Row Properties. In the Row tab, leave the default RowName, Show numbered row headers.
Add Components to the GUI Set Data Properties. Specify the value of the Data you want in the table. You need create Data in the MATLAB command window before you specify it in GUIDE. For this example, type: dat = 6.75, 7, {6.125, 456.3457, true, 'Fixed';... 510.2342, false, 'Adjustable';... false, 'Fixed';}; 658.2, In the Table Property Editor, select the data that you defined and select Change data value to the selected workspace variable below.
6 Lay Out a GUIDE GUI Set Color Properties. Specify the BackgroundColor and RowStriping for your table in the Color tab.
Add Components to the GUI You can change other uitable properties to the table via the Property Inspector. Add ActiveX Controls When you drag an ActiveX component from the component palette into the layout area, GUIDE opens a dialog box, similar to the following, that lists the registered ActiveX controls on your system.
6 Lay Out a GUIDE GUI Note If MATLAB software is not installed locally on your computer — for example, if you are running the software over a network — you might not find the ActiveX control described in this example. To register the control, see “Registering Controls and Servers”. 1 Select the desired ActiveX control. The right panel shows a preview of the selected control.
Add Components to the GUI 2 Click Create. The control appears as a small box in the Layout Editor. 3 Resize the control to approximately the size of the square shown in the preview pane. You can do this by clicking and dragging a corner of the control, as shown in the following figure. When you select an ActiveX control, you can open the ActiveX Property Editor by right-clicking and selecting ActiveX Property Editor from the context menu or clicking the Tools menu and selecting it from there.
6 Lay Out a GUIDE GUI • “Select Components” on page 6-80 • “Copy, Cut, and Clear Components” on page 6-81 • “Paste and Duplicate Components” on page 6-81 • “Front-to-Back Positioning” on page 6-82 Other topics that may be of interest are • “Locate and Move Components” on page 6-83 • “Resize Components” on page 6-86 • “Align Components” on page 6-89 • “Set Tab Order” on page 6-98 Select Components You can select components in the layout area in the following ways: • Click a single component to select it.
Add Components to the GUI Note You can select multiple components only if they have the same parent. To determine the child objects of a figure, panel, or button group, use the Object Browser. Copy, Cut, and Clear Components Use standard menu and pop-up menu commands, toolbar icons, keyboard keys, and shortcut keys to copy, cut, and clear components. Copy. Copying places a copy of the selected components on the clipboard. A copy of a panel or button group includes its children. Cut.
6 Lay Out a GUIDE GUI the selected components. Look for the highlight as described in “Add a Component to a Panel or Button Group” on page 6-34.
Add Components to the GUI • 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). • Bring Forward — Move the selected object(s) forward by one level, i.e., in front of the object directly forward of it, but not in front of all objects that overlay it (available from the Layout menu). • Send Backward — Move the selected object(s) back by one level, i.e.
6 Lay Out a GUIDE GUI If you drag or resize the component, the readout updates accordingly. The readout to the left of the component position readout displays the current mouse position, also in pixels. The following readout example shows a selected component that has a position of [35, 30, 180, 180], a 180-by-180 pixel object with a lower left corner at x=35 and y=30, and locates the mouse position at [200, 30].
Add Components to the GUI Use Arrow Keys to Move Components Select one or more components that you want to move, then press and hold the arrow keys until the components have moved to the desired position. Note that the components remain children of the figure, panel, or button group from which you move them, even if they move outside its boundaries. Set the Component’s Position Property Select one or more components that you want to move.
6 Lay Out a GUIDE GUI 2 Click the + sign next to Position. The Property Inspector displays the elements of the Position property. 3 If you have selected • Only one component, type the x and y coordinates of the point where you want the lower-left corner of the component to appear. • More than one component, type either the x or the y coordinate to align the components along that dimension. 4 Reset the Units property to its previous setting, either characters or normalized.
Add Components to the GUI Drag a Corner of the Component Select the component you want to resize. Click one of the corner handles and drag it until the component is the desired size. Set the Component’s Position Property Select one or more components that you want to resize. Then open the Property Inspector from the View menu or by clicking the Property Inspector button . 1 In the Property Inspector, scroll to the Units property and note whether the current setting is characters or normalized.
6 Lay Out a GUIDE GUI 2 Click the + sign next to Position. The Property Inspector displays the elements of the Position property. 3 Type the width and height you want the components to be. 4 Reset the Units property to its previous setting, either characters or normalized. Note To select multiple components, they must have the same parent. That is, they must be contained in the same figure, panel, or button group. See “Select Components” on page 6-80 for more information.
Align Components Align Components In this section... “Align Objects Tool” on page 6-89 “Property Inspector” on page 6-92 “Grid and Rulers” on page 6-96 “Guide Lines” on page 6-96 Align Objects Tool The Align Objects tool enables you to position objects with respect to each other and to adjust the spacing between selected objects. The specified alignment operations apply to all components that are selected when you press the Apply button.
6 Lay Out a GUIDE GUI The Align Objects 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. In many cases, it is better to apply alignments independently to the vertical and horizontal using two separate steps.
Align Components Align Options There are both vertical and horizontal align options. Each option aligns selected components to a reference line, which is determined by the bounding box that encloses the selected objects. For example, the following picture of the layout area shows the bounding box (indicated by the dashed line) formed by three selected push buttons.
6 Lay Out a GUIDE GUI Both modes enable you to specify how the spacing is measured, as indicated by the button labels on the alignment tool. These options include spacing measured with respect to the following edges: • Vertical — inner, top, center, and bottom • Horizontal — inner, left, center, and right Property Inspector About the Property Inspector In GUIDE, as in MATLAB generally, you can see and set most components’ properties using the Property Inspector.
Align Components Scroll down to see additional properties. Click any property value or icon to the left of one to set its value, either directly in that field or via a modal GUI such as a pop-up menu, text dialog, or color picker. Click the plus boxes on the left margin to expand multiline properties, such as BackgroundColor, Extent, and Position.
6 Lay Out a GUIDE GUI The Property Inspector provides context-sensitive help for individual properties. Right-clicking a property name or value opens a context menu item saying What’s This?. Clicking it opens a Help window displaying documentation for the property you selected. For example, on the right is context-sensitive help for the push button ButtonDownFcn obtained from the Property Inspector as shown on the left.
Align Components 2 Select Property Inspector from the View menu or click the Property Inspector button . 3 In the Property Inspector, scroll to the Units property and note its current setting, then change the setting to inches. 4 Scroll to the Position property. A null value means that the element differs in value for the different components. This figure shows the Position property for multiple components of the same size. 5 Change the value of x to align their left sides.
6 Lay Out a GUIDE GUI Grid and Rulers The layout area displays a grid and rulers to facilitate component layout. Grid lines are spaced at 50-pixel intervals by default and you can select from a number of other values ranging from 10 to 200 pixels. You can optionally enable snap-to-grid, which causes any object that is moved close to a grid line to jump to that line. Snap-to-grid works with or without a visible grid.
Align Components Creating Guide Lines To create a guide line, click the top or left ruler and drag the line into the layout area.
6 Lay Out a GUIDE GUI Set Tab Order A GUI’s tab order is the order in which components of the GUI acquire focus when a user presses the Tab key on the keyboard. Focus is generally denoted by a border or a dotted border. You can set, independently, the tab order of components that have the same parent. The GUI figure and each panel and button group in it has its own tab order. For example, you can set the tab order of components that have the figure as a parent.
Set Tab Order The figure in the following GUI contains an axes component, a slider, a panel, static text, and a pop-up menu. Of these, only the slider, the panel, and the pop-up menu at the figure level can be tabbed. The panel contains three push buttons, which can all be tabbed.
6 Lay Out a GUIDE GUI 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.
Create Menus in a GUIDE GUI Create Menus in a GUIDE GUI In this section... “Menus for the Menu Bar” on page 6-102 “Context Menus” on page 6-114 You can use GUIDE to give GUIs menu bars with pull-down menus as well as context menus that you attach to components. You can create both types of menus using the Menu Editor. Access the Menu Editor from the Tools menu or click the Menu Editor button .
6 Lay Out a GUIDE GUI Note See “Menu Item” on page 8-59 and “Updating a Menu Item Check” on page 8-61 for information about programming and basic examples.
Create Menus in a GUIDE GUI • “Create a Menu” on page 6-106 • “Add Items to a Menu” on page 6-109 • “Additional Drop-Down Menus” on page 6-111 • “Cascading Menus” on page 6-112 When you create a drop-down menu, GUIDE adds its title to the GUI menu bar. You then can create menu items for that menu. Each menu item can have a cascading menu, also known as a submenu, and these items can have cascading menus, and so on.
6 Lay Out a GUIDE GUI The WindowStyle figure property also affects docking behavior. The default is 'normal', but if you change it to 'docked', then the following applies: • The GUI opens docked in the desktop when you run it. • The DockControls property is set to 'on' and cannot be turned off until WindowStyle is no longer set to 'docked'.
Create Menus in a GUIDE GUI In either case, you can enable users of your GUI to dock and undock it using its docking arrow by setting the figure’s DockControls property to 'on'.
6 Lay Out a GUIDE GUI Create a Menu 1 Start a new menu by clicking the New Menu button in the toolbar. A menu title, Untitled 1, appears in the left pane of the dialog box. Note By default, GUIDE selects the Menu Bar tab when you open the Menu Editor.
Create Menus in a GUIDE GUI 2 Click the menu title to display a selection of menu properties in the right pane. 3 Fill in the Label and Tag fields for the menu. For example, set Label to File and set Tag to file_menu. Click outside the field for the change to take effect. Label is a string that specifies the text label for the menu item. To display the & character in a label, use two & characters in the string.
6 Lay Out a GUIDE GUI remove, default, and factory (case sensitive) are reserved. To use one of these as labels, prepend a backslash (\) to the string. For example, \remove yields remove. Tag is a string that is an identifier for the menu object. It is used in the code to identify the menu item and must be unique in the GUI.
Create Menus in a GUIDE GUI Add Items to a Menu Use the New Menu Item tool to create menu items that are displayed in the drop-down menu. 1 Add an Open menu item under File, by selecting File then clicking the New Menu Item button in the toolbar. A temporary numbered menu item label, Untitled, appears.
6 Lay Out a GUIDE GUI 2 Fill in the Label and Tag fields for the new menu item. For example, set Label to Open and set Tag to menu_file_open. Click outside the field for the change to take effect. You can also • Choose an alphabetic keyboard accelerator for the menu item with the Accelerator pop-up menu. In combination with Ctrl, this is the keyboard equivalent for a menu item that does not have a child menu.
Create Menus in a GUIDE GUI some accelerators may be used for other purposes on your system and that other actions may result. • Display a separator above the menu item by checking Separator above this item. • Display a check next to the menu item when the menu is first opened by checking Check mark this item. A check indicates the current state of the menu item. See the example in “Add Items to the Context Menu” on page 6-116. • Enable this item when the menu is first opened by checking Enable this item.
6 Lay Out a GUIDE GUI Cascading Menus To create a cascading menu, select the menu item that will be the title for the cascading menu, then click the New Menu Item button. In the example below, Copy is a cascading menu.
Create Menus in a GUIDE GUI Note See “Menu Item” on page 8-59 for information about programming menu items. The following Menu Editor illustration shows three menus defined for the figure menu bar. When you run the GUI, the menu titles appear in the menu bar.
6 Lay Out a GUIDE GUI Context Menus A context menu is displayed when a user right-clicks the object for which the menu is defined. The Menu Editor enables you to define context menus and associate them with objects in the layout. The process has three steps: 1 “Create the Parent Menu” on page 6-114 2 “Add Items to the Context Menu” on page 6-116 3 “Associate the Context Menu with an Object” on page 6-120 Note See “Menus for the Menu Bar” on page 6-102 for information about defining menus in general.
Create Menus in a GUIDE GUI 1 Select the Menu Editor’s Context Menus tab and select the New Context Menu button from the toolbar.
6 Lay Out a GUIDE GUI 2 Select the menu and specify the Tag field to identify the context menu (axes_context_menu in this example). Add Items to the Context Menu Use the New Menu Item button to create menu items that are displayed in the context menu. 1 Add a Blue background color menu item to the menu by selecting axes_context_menu and clicking the New Menu Item tool. A temporary numbered menu item label, Untitled, appears.
Create Menus in a GUIDE GUI 6-117
6 Lay Out a GUIDE GUI 2 Fill in the Label and Tag fields for the new menu item. For example, set Label to Blue background color and set Tag to blue_background. Click outside the field for the change to take effect. You can also • Display a separator above the menu item by checking Separator above this item. • Display a check next to the menu item when the menu is first opened by checking Check mark this item. A check indicates the current state of the menu item.
Create Menus in a GUIDE GUI opened. If you clear this option, the menu item appears dimmed when the menu is first opened, and the user cannot select it. • Specify a Callback for the menu that performs the action associated with the menu item. If you have not yet saved the GUI, the default value is %automatic. When you save the GUI, and if you have not changed this field, GUIDE automatically creates a callback in the code file using a combination of the Tag field and the GUI filename.
6 Lay Out a GUIDE GUI The View button displays the callback, if there is one, in an editor. If you have not yet saved the GUI, GUIDE prompts you to save it. • Open the Property Inspector, where you can change all menu properties except callbacks, by clicking the More options button. For detailed information about these properties, see Uicontextmenu Properties . Associate the Context Menu with an Object 1 In the Layout Editor, select the object for which you are defining the context menu.
Create Menus in a GUIDE GUI Note See “Menu Item” on page 8-59 and “Updating a Menu Item Check” on page 8-61 for programming information and basic examples.
6 Lay Out a GUIDE GUI Create Toolbars In this section... “Create Toolbars with GUIDE” on page 6-122 “Editing Tool Icons” on page 6-131 Create Toolbars with GUIDE You can add a toolbar to a GUI you create in GUIDE with the Toolbar Editor, which you open from the GUIDE Layout Editor toolbar. You can also open the Toolbar Editor from the Tools menu.
Create Toolbars The Toolbar Editor gives you interactive access to all the features of the uitoolbar, uipushtool, and uitoggletool functions. It only operates in the context of GUIDE; you cannot use it to modify any of the built-in MATLAB toolbars. However, you can use the Toolbar Editor to add, modify, and delete a toolbar from any GUI in GUIDE. Currently, you can add one toolbar to your GUI in GUIDE. However, your GUI can also include the standard MATLAB figure toolbar.
6 Lay Out a GUIDE GUI Note You do not need to use the Toolbar Editor if you simply want your GUI to have a standard figure toolbar. You can do this by setting the figure’s ToolBar property to 'figure', as follows: 1 Open the GUI in GUIDE. 2 From the View menu, open Property Inspector. 3 Set the ToolBar property to 'figure' using the drop-down menu. 4 Save the figure If you later want to remove the figure toolbar, set the ToolBar property to 'auto' and resave the GUI.
Create Toolbars To add a tool, drag an icon from the Tool Palette into the Toolbar Layout (which initially contains the text prompt shown above), and edit the tool’s properties in the Tool Properties pane.
6 Lay Out a GUIDE GUI When you first create a GUI, no toolbar exists on it. When you open the Toolbar Editor and place the first tool, a toolbar is created and a preview of the tool you just added appears in the top part of the window. If you later open a GUI that has a toolbar, the Toolbar Editor shows the existing toolbar, although the Layout Editor does not. Add Tools You can add a tool to a toolbar in three ways: • Drag and drop tools from the Tool Palette.
Create Toolbars Predefined and Custom Tools The Toolbar Editor provides two types of tools: 6-127
6 Lay Out a GUIDE GUI • Predefined tools, having standard icons and behaviors • Custom tools, having generic icons and no behaviors Predefined Tools. The set of icons on the bottom of the Tool Palette represent standard MATLAB figure tools. Their behavior is built in. Predefined tools that require an axes (such as pan and zoom) do not exhibit any behavior in GUIs lacking axes.
Create Toolbars Move Tools You can reorder tools on the toolbar in two ways: • Drag a tool to a new position. • Select a tool in the toolbar and click one of the arrow buttons below the right side of the toolbar. If a tool has a separator to its left, the separator moves with the tool. Remove Tools You can remove tools from the toolbar in three ways: • Select a tool and press the Delete key. • Select a tool and click the Delete button on the GUI.
6 Lay Out a GUIDE GUI See “Working with Callbacks in GUIDE” on page 8-2 for details on programming the tool callbacks. You can also access these and other properties of the selected tool with the Property Inspector. To open the Property Inspector, click the More Properties button on the Tool Properties pane. Edit Tool Icons To edit a selected toolbar icon, click the Edit button in the Tool Properties pane, next to CData (icon) or right-click the Toolbar Layout and select Edit Icon from the context menu.
Create Toolbars Remove a Toolbar You can remove a toolbar completely—destroying it—from the Toolbar Editor, leaving your GUI without a toolbar (other than the figure toolbar, which is not visible by default). The are two ways to remove a toolbar: • Click the Remove button on the right end of the toolbar. • Right-click a blank area on the toolbar and select Remove Toolbar from the context menu.
6 Lay Out a GUIDE GUI Note There are examples that show how to create your own icon editor. See the example in “Icon Editor” on page 15-63 and the discussion of sharing data among multiple GUIs.
Create Toolbars Use the Icon Editor The Icon Editor GUI includes the following components: • Icon file name — The icon image file to be loaded for editing • Import button — Opens a file dialog to select an existing icon file for editing • Drawing tools — A group of four tools on the left side for editing icons - Pencil tool — Color icon pixels by clicking or dragging - Pick color tool — Click a pixel or color palette swatch to define the current color Eraser tool — Erase pixels to be transparent by cl
6 Lay Out a GUIDE GUI • Hold down the left mouse button and drag the mouse over the grid to transfer the selected color to the squares that you touch. • Change a color by writing over it with another color. 3 Using the Eraser tool, erase the color in some squares • Click the Eraser button on the palette. • Click in specific squares to erase those squares. • Click and drag the mouse to erase the squares that you touch. • Click a another drawing tool to disable the Eraser.
Create Toolbars 6-135
6 Lay Out a GUIDE GUI View the Object Hierarchy The Object Browser displays a hierarchical list of the objects in the figure, including both components and menus. As you lay out your GUI, check the object hierarchy periodically, especially if your GUI contains menus, panes, or button groups. Open it from View > Object Browser or by click the Object Browser icon on the GUIDE toolbar. The following illustration shows a figure object and its child objects. It also shows the child objects of a uipanel.
Designing for Cross-Platform Compatibility Designing for Cross-Platform Compatibility In this section... “Default System Font” on page 6-137 “Standard Background Color” on page 6-138 “Cross-Platform Compatible Units” on page 6-139 Default System Font By default, user interface controls (uicontrols) use the default font for the platform on which they are running. For example, when displaying your GUI on PCs, uicontrols use MS San Serif.
6 Lay Out a GUIDE GUI Specify a Fixed-Width Font If you want to use a fixed-width font for a user interface control, 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 The following figures illustrate the results with and without system color matching. Cross-Platform Compatible Units Cross-platform compatible GUIs should look correct on computers having different screen sizes and resolutions. Since the size of a pixel can vary on different computer displays, using the default figure Units of pixels does not produce a GUI that looks the same on all platforms.
6 Lay Out a GUIDE GUI Units and Resize Behavior If you set your GUI’s resize behavior from the GUI Options dialog box, GUIDE automatically sets the units for the GUI’s components in a way that maintains the intended look and feel across platforms. To specify the resize behavior option, select GUI Options from the Tools menu, then specify Resize behavior by selecting Non-resizable, Proportional, or Other (Use ResizeFcn). If you choose Non-resizable, GUIDE defaults the component units to characters.
7 Save and Run a GUIDE GUI • “Name a GUI and Its Files” on page 7-2 • “Save a GUIDE GUI” on page 7-4 • “Run a GUIDE GUI” on page 7-10
7 Save and Run a GUIDE GUI Name a GUI and Its Files In this section... “The GUI Files” on page 7-2 “File and GUI Names” on page 7-3 “Rename GUIs and GUI Files” on page 7-3 The GUI Files By default, GUIDE stores a GUI in two files which are generated the first time you save or run the GUI: • A MATLAB FIG-file, with extension .fig, that contains a complete description of the GUI layout and the GUI components, such as push buttons, axes, panels, menus, and so on.
Name a GUI and Its Files For more information about these files, see “Files Generated by GUIDE” on page 8-7. File and GUI Names The code file and the FIG-file that define your GUI must have the same name. This name is also the name of your GUI. For example, if your files are named mygui.fig and mygui.m, then the name of the GUI is mygui, and you can run the GUI by typing mygui at the command line. This assumes that the code file and FIG-file are in the same folder and that the folder is in your path.
7 Save and Run a GUIDE GUI Save a GUIDE GUI In this section... “Ways to Save a GUI” on page 7-4 “Save a New GUI” on page 7-5 “Save an Existing GUI” on page 7-8 “Export a GUIDE GUI to a Code File” on page 7-9 Ways to Save a GUI You can save a GUI in GUIDE in any of these ways: • From the GUIDE Quick Start dialog box. Before you select a template, GUIDE lets you select a name for your GUI. When you click OK, GUIDE saves the GUI code file and FIG-file using the name you specify.
Save a GUIDE GUI In either case, GUIDE prompts you for a name before saving the GUI, and saves both a .fig file and a .m file using the name you specify, for example, mygui.fig and mygui.m, • The first time you run the GUI by - Clicking the Run icon on the Layout Editor toolbar Selecting Run from the Tools menu In each case, GUIDE prompts you for a name and saves the GUI files before activating the GUI. In all cases, GUIDE opens a template for your code in your default editor.
7 Save and Run a GUIDE GUI Note If you select Save as from the File menu or click the Save button on the toolbar, GUIDE saves the GUI without activating it. However, if you select Run from the Tools menu or click the Run icon on the toolbar, GUIDE saves the GUI before activating it. 1 If you have made changes to the GUI and elect to activate the GUI by selecting Run from the Tools menu or by clicking the Run icon on the toolbar, GUIDE displays the following dialog box. Click Yes to continue.
Save a GUIDE GUI 4 If you choose an existing filename, GUIDE displays a dialog box that asks you if you want to replace the existing FIG-file. Click Yes to continue. 5 If you chose Yes in the previous step, GUIDE displays a dialog that asks if you want to replace the existing code file or append to it. The most common choice is Replace. If you choose Append, GUIDE adds callbacks to the existing code file for components in the current layout that are not present within it.
7 Save and Run a GUIDE GUI 6 If you chose to activate the GUI by selecting Run from the Tools menu or by clicking the Run button on the toolbar, and if the folder in which you save the GUI is not on the MATLAB path, GUIDE opens a dialog box, giving you the option of changing the current working folder to the folder containing the GUI files, or adding that folder to the top or bottom of the MATLAB path. 7 After you save the files, GUIDE opens the GUI code file in your default editor.
Save a GUIDE GUI If you select Save from the File menu or click the Save button toolbar, GUIDE saves the GUI without activating it. on the Export a GUIDE GUI to a Code File Saving a GUIDE GUI using File > Save or File > Save as generates a MATLAB code file and a FIG-file. Both files must be on the search path in order to run the GUI. GUIDE also gives you the option to export a GUI to a single code file. The code recreates the GUI layout programmatically.
7 Save and Run a GUIDE GUI Run a GUIDE GUI In this section... “Execute GUI Code” on page 7-10 “From the GUIDE Layout Editor” on page 7-10 “From the Command Line” on page 7-11 “From Any MATLAB Code File” on page 7-11 “From a Test Script” on page 7-12 Execute GUI Code In most cases, you run your GUI by executing the code file that GUIDE generates by typing its name in the Command Window. This file loads the GUI figure and provides a framework for the component callbacks.
Run a GUIDE GUI In either case, if the GUI has changed or has never been saved, GUIDE saves the GUI files before activating it and opens the GUI code file in your default editor. See “Save a GUIDE GUI” on page 7-4 for information about this process. See “Files Generated by GUIDE” on page 8-7 for more information about GUI code files. From the Command Line Run your GUI by executing its code file. For example, if your GUI code file is mygui.m, enter: mygui at the command line.
7 Save and Run a GUIDE GUI The GUI files must reside on the MATLAB path or in the current MATLAB folder where the GUI is run. If a GUI accepts arguments when it is run, they are passed to the GUI’s opening function. See “Opening Function” on page 8-25 for more information. Note Consider whether you want to allow more than one copy of the GUI to be active at the same time.
Run a GUIDE GUI for val = 1:3 set(handles.plot_popup,'Value',val) simple_gui('plot_popup_Callback',... handles.plot_popup,[],handles) % Refresh handles after changing data handles = guidata(hfig); % Call contour push button callback simple_gui('contour_pushbutton_Callback',... handles.contour_pushbutton,[],handles) pause(1) % Call surf push button callback simple_gui('surf_pushbutton_Callback',... handles.
7 7-14 Save and Run a GUIDE GUI
8 Programming a GUIDE GUI • “Working with Callbacks in GUIDE” on page 8-2 • “Files Generated by GUIDE” on page 8-7 • “Default Callback Properties in GUIDE” on page 8-11 • “Customizing Callbacks in GUIDE” on page 8-15 • “Initialize a GUIDE GUI” on page 8-25 • “Add Code for Components in Callbacks” on page 8-30
8 Programming a GUIDE GUI Working with Callbacks in GUIDE In this section... “Programming GUIs Created Using GUIDE” on page 8-2 “What Is a Callback?” on page 8-2 “Kinds of Callbacks” on page 8-2 Programming GUIs Created Using GUIDE After you have laid out your GUI, program its behavior. The code you write controls how the GUI responds to events. Events include button clicks, slider movements, menu item selections, and the creation and deletion of components.
Working with Callbacks in GUIDE of that component. For example, a push button has five callback properties: ButtonDownFcn, Callback, CreateFcn, DeleteFcn, and KeyPressFcn. A panel has four callback properties: ButtonDownFcn, CreateFcn, DeleteFcn, and ResizeFcn. You can—but do not have to—create a callback function for each of these properties, including callbacks for the GUI figure itself. Each callback has a triggering mechanism or event that causes it to execute.
8 8-4 Programming a GUIDE GUI Callback Property Triggering Event Components CreateFcn Initializes the component when a function creates it. It executes after the component or figure is created, but before it displays. Axes, button group, context menu, figure, menu, panel, push tool, toggle tool, toolbar, user interface controls DeleteFcn Performs cleanup operations just before the component or figure is destroyed.
Working with Callbacks in GUIDE Callback Property Triggering Event Components SelectionChangeFcn Executes when a GUI user selects a different radio button or toggle button in a button group component. Button group WindowButtonDownFcn Executes when you press a mouse button while the pointer is in the figure window. Figure WindowButtonMotionFcn Executes when you move the pointer within the figure window. Figure WindowButtonUpFcn Executes when you release a mouse button.
8 Programming a GUIDE GUI Note User interface controls include push buttons, sliders, radio buttons, check boxes, editable text boxes, static text boxes, list boxes, and toggle buttons. They are sometimes referred to as uicontrols.
Files Generated by GUIDE Files Generated by GUIDE In this section... “Code Files and FIG-Files” on page 8-7 “GUI Code File Structure” on page 8-8 “Adding Callback Templates to an Existing GUI Code File” on page 8-9 “About GUIDE-Generated Callbacks” on page 8-9 Code Files and FIG-Files By default, the first time you save or run a GUI, GUIDE stores the GUI in two files: • A FIG-file, with extension .
8 Programming a GUIDE GUI For more information, see “Name a GUI and Its Files” on page 7-2,“Save a GUIDE GUI” on page 7-4, and“Rename GUIs and GUI Files” on page 7-3. GUI Code File Structure The GUI code file that GUIDE generates is a function file. The name of the main function is the same as the name of the code file. For example, if the name of the code file is mygui.m, then the name of the main function is mygui. Each callback in the file is a subfunction of that main function.
Files Generated by GUIDE Adding Callback Templates to an Existing GUI Code File When you save the GUI, GUIDE automatically adds templates for some callbacks to the code file. If you want to add other callbacks to the file, you can easily do so. Within GUIDE, you can add a callback subfunction template to the code in any of the following ways. Select the component for which you want to add the callback, and then: • Click the right mouse button to display the Layout Editor context menu.
8 Programming a GUIDE GUI GUIDE names callbacks based on the callback type and the component Tag property. For example, togglebutton1_Callback is such a default callback name. If you change a component Tag, GUIDE renames all its callbacks in the code file to contain the new tag. You can change the name of a callback, replace it with another function, or remove it entirely using the Property Inspector. • GUIDE provides three arguments to callbacks, always named the same.
Default Callback Properties in GUIDE Default Callback Properties in GUIDE In this section... “Setting Callback Properties Automatically” on page 8-11 “Deleting Callbacks from a GUI Code File” on page 8-14 Setting Callback Properties Automatically A GUI can have many components. GUIDE provides a way of specifying which callback runs in response to a particular event for a particular component. The callback that runs when the GUI user clicks a Yes button is not the one that runs for the No button.
8 Programming a GUIDE GUI The following figure shows properties of a push button in the GUIDE Property Inspector prior to saving the GUI. GUIDE set the Tag property to pushbutton1. Before saving the GUI, Callback property displays as %automatic, indicating that GUIDE will generate a name for it when you save the GUI. Note If you change the string %automatic before saving the GUI, GUIDE does not automatically add a callback for that component or menu item. It is up to you to provide a callback yourself.
Default Callback Properties in GUIDE When you save the GUI, GUIDE constructs the name of the callback by appending an underscore (_) and the name of the callback property to the value of the component’s Tag property.
8 Programming a GUIDE GUI When you save the GUI, GUIDE also opens the GUI code file in your editor. The file then contains a template for the Callback callback for the component whose Tag is pushbutton1. If you activate the GUI, clicking the push button triggers the execution of the Callback callback for the component. For information about changing the callback name after GUIDE assigns it, see “Changing Callbacks Assigned by GUIDE” on page 8-22.
Customizing Callbacks in GUIDE Customizing Callbacks in GUIDE In this section... “GUIDE Callback Templates” on page 8-15 “Callback Names and Signatures in GUIDE” on page 8-16 “GUIDE Callback Arguments” on page 8-20 “Changing Callbacks Assigned by GUIDE” on page 8-22 GUIDE Callback Templates GUIDE defines conventions for callback syntax and arguments and implements these conventions in the callback templates it adds to the GUI code.
8 Programming a GUIDE GUI % Modifier: name(s) of the modifier key(s)(i.e., control, shift) % pressed % handles structure with handles and user data (see GUIDATA) Callbacks that provide event data and the components to which they apply are listed in the following table. See the appropriate property reference pages for detailed information.
Customizing Callbacks in GUIDE property for the push button, and Callback is one of the push button’s callback properties. The Tag property uniquely identifies a component within the GUI. The first time you save the GUI after adding a component, GUIDE adds callbacks for that component to the code file and generates the callback names using the current value of the Tag property.
8 Programming a GUIDE GUI @(hObject,eventdata)mygui('pushbutton1_Callback',hObject,eventdata,guidata(hObject)) The syntax @(hObject,eventdata) indicates that this is an anonymous function. The signature enables MATLAB to execute the right callback when the user clicks this push button by providing the following information.
Customizing Callbacks in GUIDE Saving a GUI with a push button in GUIDE... creates a callback template in mygui.m ... having this signature ... @(hObject,eventdata)mygui('pushbutton1_Callback',hObject,eventdata,guidata(hObject)) that displays in the Property Inspector like this See “GUIDE Callback Arguments” on page 8-20 for details about GUIDE-generated callbacks.
8 Programming a GUIDE GUI GUIDE Callback Arguments All callbacks in a GUIDE-generated GUI code file have the following standard input arguments: • hObject — Handle of the object, e.g., the GUI component, for which the callback was triggered. For a button group SelectionChangeFcn callback, hObject is the handle of the selected radio button or toggle button.
Customizing Callbacks in GUIDE • KeyPressFcn in uicontrols and figures • KeyReleaseFcn in a figure • SelectionChangeFcn in a uibuttongroup • WindowKeyPressFcn in a figure or any of its child objects • WindowKeyReleaseFcn in a figure or any of its child objects • WindowScrollWheelFcn in a figure Event data is passed to GUIDE-generated callbacks as the second of three standard arguments. For components that issue no event data the argument is empty.
8 Programming a GUIDE GUI the programmatic uitable example “GUI that Displays and Graphs Tabular Data” on page 15-19. handles Structure GUIDE creates a handles structure that contains the handles of all the objects in the figure. For a GUI that contains an edit text, a panel, a pop-up menu, and a push button, the handles structure originally looks similar to this. GUIDE uses each component’s Tag property to name the structure element for its handle.
Customizing Callbacks in GUIDE warnbeforesave. If possible, change the Tag property before saving the GUI to cause GUIDE to automatically create callback templates having names you prefer.
8 Programming a GUIDE GUI Click Yes to revert to the GUIDE auto-generated callback. click No to keep the modified callback. Note Remember to change the callback function definition in the GUI code file if you change its signature in the Property Inspector unless you are pointing a callback to another function that exists in that file. For example, you might want several toggle buttons or menu items to use the same callback.
Initialize a GUIDE GUI Initialize a GUIDE GUI In this section... “Opening Function” on page 8-25 “Output Function” on page 8-28 Opening Function The opening function is the first callback in every GUI code file. It is executed just before the GUI is made visible to the user, but after all the components have been created, i.e., after the components’ CreateFcn callbacks, if any, have been run. You can use the opening function to perform your initialization tasks before the user has access to the GUI.
8 Programming a GUIDE GUI % Update handles structure guidata(hObject, handles); % UIWAIT makes mygui wait for user response (see UIRESUME) % uiwait(handles.mygui); Input Arguments The opening function has four input arguments hObject, eventdata, handles, and varargin. The first three are the same as described in “GUIDE Callback Arguments” on page 8-20. the last argument, varargin, enables you to pass arguments from the command line to the opening function.
Initialize a GUIDE GUI GUI template, available from the GUIDE Quick Start dialog box. The added code opens the modal dialog with a message, specified from the command line or by another GUI that calls this one. For example, mygui('String','Do you want to exit?') displays the text 'Do you want to exit?' on the GUI. To do this, you need to customize the opening function because 'String' is not a valid figure property, it is a static text property.
8 Programming a GUIDE GUI . . . The if block loops through the odd elements of varargin checking for property names or aliases, and the case blocks assign the following (even) varargin element as a value to the appropriate property of the figure or one of its components. You can add more cases to handle additional property assignments that you want the opening function to perform. Initial Template Code Initially, the input function template contains these lines of code: • handles.
Initialize a GUIDE GUI Function Naming and Template GUIDE names the output function by appending _OutputFcn to the name of the GUI. This is an example of an output function template as it might appear in the mygui code file. % --- Outputs from this function are returned to the command line. function varargout = mygui_OutputFcn(hObject, eventdata,...
8 Programming a GUIDE GUI Add Code for Components in Callbacks In this section...
Add Code for Components in Callbacks This is the push button’s Callback callback. It displays the string Goodbye at the command line and then closes the GUI. function pushbutton1_Callback(hObject, eventdata, handles) display Goodbye close(handles.figure1); Adding an Image to a Push Button or Toggle Button To add an image to a push button or toggle button, assign the button’s CData property an m-by-n-by-3 array of RGB values that defines “RGB (Truecolor) Images”.
8 Programming a GUIDE GUI button_state = get(hObject,'Value'); if button_state == get(hObject,'Max') % Toggle button is pressed, take appropriate action ... elseif button_state == get(hObject,'Min') % Toggle button is not pressed, take appropriate action ... end You can also change the state of a toggle button programmatically by setting the toggle button Value property to the value of its Max or Min property. This example illustrates a possible syntax for such an assignment. set(handles.
Add Code for Components in Callbacks selects the radio button with Tag property radiobutton1 and deselects the previously selected radio button. Note You can use a button group to manage exclusive selection behavior for radio buttons. See “Button Group” on page 8-42 for more information. Check Box You can determine the current state of a check box from within its callback by querying the state of its Value property.
8 Programming a GUIDE GUI If the edit text Max and Min properties are set such that Max - Min > 1, the user can enter multiple lines. For example, setting Max to 2, with the default value of 0 for Min, enables users to enter multiple lines. Retrieving Numeric Data from an Edit Text Component MATLAB software returns the value of the edit text String property as a character string. If you want users to enter numeric values, you must convert the characters to numbers.
Add Code for Components in Callbacks Available Keyboard Accelerators GUI users can use the following keyboard accelerators to modify the content of an edit text. These accelerators are not modifiable. • Ctrl+X — Cut • Ctrl+C — Copy • Ctrl+V — Paste • Ctrl+H — Delete last character • Ctrl+A — Select all Table A table can contain numbers, character data, and preset choices (drop-down menus). Each column must contain the same type of data.
8 Programming a GUIDE GUI Table CellSelectionCallback Every time the user selects a table cell, the table’s CellSelectionCallback fires. This happens whether table cells are editable or not. When cells are not editable, users can drag across a range of cells to select them all. When cells are editable, users can select more than one cell at a time using Shift+click or Ctrl+click, but not by dragging.
Add Code for Components in Callbacks selects the second item in the list box with Tag property listbox1. Triggering Callback Execution MATLAB software executes the list box’s Callback callback after the mouse button is released or after certain key press events: • The arrow keys change the Value property, trigger callback execution, and set the figure SelectionType property to normal.
8 Programming a GUIDE GUI Using Only the Index of the Selected Menu Item This example retrieves only the index of the item selected. It uses a switch statement to take action based on the value. If the contents of the pop-up menu are fixed, then you can use this approach. Else, you can use the index to retrieve the actual string for the selected item.
Add Code for Components in Callbacks groups as well as axes and user interface controls such as push buttons, sliders, pop-up menus, etc. The position of each component within a panel is interpreted relative to the lower-left corner of the panel. Generally, if the GUI is resized, the panel and its components are also resized. However, you can control the size and position of the panel and its components.
8 Programming a GUIDE GUI 2 Create callbacks for the two push buttons, and place the following line of code in each of them. set(gcbf,'Position',[420 520 150 190]) This resets the GUI to its initial size, so you can experiment with resizing it manually. 3 In the Property Inspector, set the Units of the panel and the two buttons to normalized. Also set the fontSize of both buttons to 10. Make sure that the fontUnits property for both buttons is set to points.
Add Code for Components in Callbacks set(buttons(1),'FontSize',newFontSize); % Resize the first button % Do not resize the other button for comparison This code adjusts the size of one of the buttons label (in this instance, the bottom one) when the figure resizes. It computes newFontSize as the ratio of the panel’s current size to its original size (expressed in points) multiplied by the original button fontSize, 10 points. Then it sets one of the button’s fontSize to that value.
8 Programming a GUIDE GUI Tip You can enable text in controls to resize automatically by setting the component’s fontUnits to normalized, without the need for a ResizeFcn. This example illustrates one way to achieve the same result with callback code. Nested panels resize from inner to outer (in child-to-parent order). For more information about resizing panels, see the uipanel properties reference page.
Add Code for Components in Callbacks If a user clicks the other radio button or one of the toggle buttons, it becomes selected and Radio Button 1 is deselected. The following figure shows the result of clicking Toggle Button 2. The button group’s SelectionChangeFcn callback is called whenever a selection is made. Its hObject input argument contains the handle of the selected radio button or toggle button.
8 Programming a GUIDE GUI • Select SelectionChangeFcn from the View > View Callbacks submenu, or • Right-click and select SelectionChangeFcn from the View Callbacks context menu item GUIDE places a SelectionChangeFcn callback template at the end of the GUI code file for you to complete. The following example shows how to code a SelectionChangeFcn callback. It uses the Tag property of the selected object to choose the appropriate code to execute.
Add Code for Components in Callbacks Axes Axes components enable your GUI to display graphics, such as graphs and images. This topic briefly tells you how to plot to axes components in your GUI. • “Plotting to an Axes” on page 8-45 • “Creating Subplots” on page 8-47 Plotting to an Axes In most cases, you create a plot in an axes from a callback that belongs to some other component in the GUI. For example, pressing a button might trigger the plotting of a graph to an axes.
8 Programming a GUIDE GUI 1 Add this code to the Plot 1 push button’s Callback callback. The surf function produces a 3-D shaded surface plot. The peaks function returns a square matrix obtained by translating and scaling Gaussian distributions. surf(handles.axes1,peaks(35)); 2 Add this code to the Plot 2 push button’s Callback callback. The contour function displays the contour plot of a matrix, in this case the output of peaks. contour(handles.
Add Code for Components in Callbacks Note For information about properties that you can set to control many aspects of axes behavior and appearance, see “Axes Objects — Defining Coordinate Systems for Graphs”. If your GUI contains axes, you should make sure that the Command-line accessibility option in the GUI Options dialog box is set to Callback (the default). From the Layout Editor select Tools > GUI Options > Command Line Accessibility: Callback.
8 Programming a GUIDE GUI Tip When working with multiple axes, it is best not to “raise” the axes you want to plot data into with commands like axes(a1) This will make axes a1 the current axes, but it also restacks figures and flushes all pending events, which consumes computer resources and is rarely necessary for a callback to do. It is more efficient to simply supply the axes handle as the first argument of the plotting function you are calling, such as plot(a1, ...
Add Code for Components in Callbacks For more information about subplots, see the subplot reference page. For information about adding panels to your GUI, see “Add Components to the GUIDE Layout Area” on page 6-31. ActiveX Control This example programs a sample ActiveX control Mwsamp Control. It first enables a user to change the radius of a circle by clicking on the circle. It then programs a slider on the GUI to do the same thing.
8 Programming a GUIDE GUI 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 Mwsamp GUI in the Layout Editor. • Click here to display the Mwsamp GUI code file in the MATLAB Editor.
Add Code for Components in Callbacks Note Clicking Create places a copy of the file Mwsamp_activex1 in your working folder. If you move your GUI files to a different folder, you should move the ActiveX controls they use with them.
8 Programming a GUIDE GUI pane. The following figure shows the ActiveX control as it appears in the Layout Editor. If you need help adding the component, see “Add ActiveX Controls” on page 6-77. 4 Activate the GUI by clicking the button on the toolbar and save the GUI when prompted. GUIDE displays the GUI shown in the following figure and opens the GUI code file.
Add Code for Components in Callbacks 5 View the ActiveX Properties with the Property Inspector. Select the control in the Layout Editor, and then select Property Inspector from the View on the toolbar. menu or by clicking the Property Inspector button The following figure shows properties of the mwsamp ActiveX control as they appear in the Property Inspector. The properties on your system may differ.
8 Programming a GUIDE GUI 7 Add the following code to the mswamp control’s activex1_Click callback. This code programs the ActiveX control to change the circle radius when the user clicks the circle, and updates the label to display the new radius. hObject.radius = floor(.9*hObject.radius); hObject.label = ['Radius = ' num2str(hObject.radius)]; refresh(handles.figure1); 8 Add the following commands to the end of the opening function, Mwsamp_OpeningFcn.
Add Code for Components in Callbacks Programming a User Interface Control to Update an ActiveX Control This topic continues the previous example by adding a slider to the GUI and programming the slider to change the circle radius. This example must also update the slider if the user clicks the circle. 1 Add a slider to your layout and then add the following code to the slider1 Callback callback: handles.activex1.radius = ... get(hObject,'Value')*handles.default_radius; handles.activex1.label = ...
8 Programming a GUIDE GUI Viewing the Methods for an ActiveX Control To view the available methods for an ActiveX control, you first need to obtain the handle to the control. One way to do this is the following: 1 In the GUI code file, add the command keyboard on a separate line of the activex1_Click callback. The command keyboard puts MATLAB software in debug mode and pauses at the activex1_Click callback when you click the ActiveX control. 2 Run the GUI and click the ActiveX control.
Add Code for Components in Callbacks Alternatively, you can enter methods(hObject) which displays the available methods in the MATLAB Command Window. For more information about methods for ActiveX controls, see “Using Methods”. See the reference pages for methodsview and methods for more information about these functions. Saving a GUI That Contains an ActiveX Control When you save a GUI that contains ActiveX controls, GUIDE creates a file in the current folder for each such control.
8 Programming a GUIDE GUI Compiling a GUI That Contains an ActiveX Control If you use the MATLAB Compiler mcc command to compile a GUI that contains an ActiveX control, you must use the -a flag to add the ActiveX file, which GUIDE saves in the current folder, to the CTF archive. Your command should be similar to mcc -m mygui -a mygui_activex1 where mygui_activex1 is the name of the ActiveX file. See the “MATLAB Compiler™” documentation for more information.
Add Code for Components in Callbacks Menu Item The GUIDE Menu Editor generates an empty callback subfunction for every menu item, including menu titles. Programming a Menu Title Because clicking a menu title automatically displays the menu below it, you may not need to program callbacks at the title level. However, the callback associated with a menu title can be a good place to enable or disable menu items below it. Consider the example illustrated in the following picture.
8 Programming a GUIDE GUI Mouse Gestures and Menu Callback Behavior. Callbacks for leaf menu items, such as for to file or to clipboard in the previous example, actuate when you release the mouse over them. Callbacks for main menus (like Edit) and non-leaf submenus (like Copy) actuate when you select them by sliding the mouse pointer into them after they display. Even when it has no menu items, a main menu callback actuates as soon as you select the menu.
Add Code for Components in Callbacks Updating a Menu Item Check A check is useful to indicate the current state of some menu items. If you selected Check mark this item in the Menu Editor, the item initially appears checked. Each time the user selects the menu item, the callback for that item must turn the check on or off. The following example shows you how to do this by changing the value of the menu item’s Checked property.
8 8-62 Programming a GUIDE GUI
9 Managing and Sharing Application Data in GUIDE • “Ways to Manage Data in a GUIDE GUI” on page 9-2 • “Making Multiple GUIs Work Together” on page 9-21
9 Managing and Sharing Application Data in GUIDE Ways to Manage Data in a GUIDE GUI In this section... “Data Management Mechanism Summary” on page 9-2 “Nested Functions” on page 9-4 “UserData Property” on page 9-5 “Application Data” on page 9-5 “GUI Data” on page 9-7 “Examples of Sharing Data Among a GUI’s Callbacks” on page 9-10 Data Management Mechanism Summary Most GUIs generate or use data specific to the application.
Ways to Manage Data in a GUIDE GUI Data-Sharing Method How it Works Use for...
9 Managing and Sharing Application Data in GUIDE • Nested Functions — Share variables defined at a higher level and call one another when called function is below above, or a sibling of the caller. • UserData Property — A MATLAB workspace variable that you assign to GUI components and retrieve like any other property. • Application Data — Provides a way for applications to save and retrieve data associated with a specified object.
Ways to Manage Data in a GUIDE GUI UserData Property All GUI components, including menus and the figure itself have a UserData property. You can assign any valid MATLAB workspace value as the UserData property’s value, but only one value can exist at a time. To retrieve the data, a callback must know the handle of the component in which the data is stored. You access UserData using get and set with the appropriate object’s handle.
9 Managing and Sharing Application Data in GUIDE Only Handle Graphics MATLAB objects use this property. The following table summarizes the functions that provide access to application data. For more details, see the individual function reference pages. Functions for Managing Application Data Function Purpose setappdata Specify named application data for an object (a figure or other Handle Graphics object in your GUI). You can specify more than one named application data for an object.
Ways to Manage Data in a GUIDE GUI Adding Fields to an Application Data Structure in GUIDE Application data is usually defined as a structure. This enables you to add fields as necessary. In this example, a push button adds a field to the application data structure mydata created in the previous section: 1 Use getappdata to retrieve the structure. The name of the application data structure is mydata. It is associated with the figure whose Tag is figure1.
9 Managing and Sharing Application Data in GUIDE • GUI data is a single variable; however, when defined as a structure, you can add and remove fields. • Application data can consist of many variables, each stored under a separate unique name. • GUIDE uses GUI data to store its handles structure, to which you can add fields, but should not remove any. • You access GUI data using the guidata function, which both stores and retrieves GUI data.
Ways to Manage Data in a GUIDE GUI adds the field number_errors to the handles structure and sets it to 0. 2 Use the following command to save the data: guidata(hObject,handles) where hObject is the handle of the component for which the callback was triggered. GUIDE then automatically passes the hObject to every callback. Changing GUI Data in a Code File Generated by GUIDE In GUIDE-generated code, the handles structure always represents GUI data.
9 Managing and Sharing Application Data in GUIDE means while it is currently running, its internal state might not need to be initialized again. One way to do that is to set a flag and store it in the handles structure. The opening function can test for the existence of the flag, and perform initialization operations only if the flag does not exist.
Ways to Manage Data in a GUIDE GUI If the user types a number between 0 and 1 in the edit text component and then presses Enter or clicks outside the edit text, the callback sets handles.slider1 to the new value and the slider moves to the corresponding position. If the entry is invalid—for example, 2.5—the GUI increments the value stored in the error counter and displays a message in the edit text component that includes the count of errors.
9 Managing and Sharing Application Data in GUIDE 1 Click here to copy the files to your current folder. 2 Type guide sliderbox_userdata or click here to open the GUI in GUIDE. 3 Type edit sliderbox_userdata or click here to open the GUI code file in the Editor. You can view the properties of any component by double-clicking it in the Layout Editor to open the Property Inspector for it. You can modify either the figure, GUI code, or both.
Ways to Manage Data in a GUIDE GUI This section shows you how to use GUI data to initialize and maintain an error counter by storing an error count in the edit text component’s UserData property. 1 Add the following code to the opening function to initialize the edit text component’s UserData property. This code initializes the data in a structure to allow for other data that could be needed: % INITIALIZE ERROR COUNT AND USE EDITTEXT1 OBJECT'S USERDATA TO STORE IT. data.number_errors = 0; set(handles.
9 Managing and Sharing Application Data in GUIDE set(hObject,'UserData',data); % Display new total. set(hObject,'String',... ['You have entered an invalid entry ',... num2str(data.number_errors),' times.']); % Restore focus to the edit text box after error uicontrol(hObject) end To update the number of errors, the code must first retrieve the value of the edit text UserData property, and then it must increment the count.
Ways to Manage Data in a GUIDE GUI 2 Type guide sliderbox_appdata or click here to open the GUI in GUIDE. 3 Type edit sliderbox_appdata or click here to open the GUI code file in the Editor. You can view the properties of any component by double-clicking it in the Layout Editor to open the Property Inspector for it. You can modify either the figure, the code, or both. Then you can save the GUI in your current folder using File > Save as from GUIDE.
9 Managing and Sharing Application Data in GUIDE The section “Sharing Data with GUI Data” on page 9-17 uses GUI data to initialize and maintain an error counter. This example shows you how to do the same thing using application data: 1 Define the error counter in the opening function by adding the following code to the opening function: % INITIALIZE ERROR COUNT AND USE APPDATA API TO STORE IT IN FIGURE. slider_data.
Ways to Manage Data in a GUIDE GUI slider_data = getappdata(handles.figure1,'slider'); slider_data.number_errors = slider_data.number_errors+1; % Save the changes. setappdata(handles.figure1,'slider',slider_data); % Display new total. set(hObject,'String',... ['You have entered an invalid entry ',... num2str(slider_data.number_errors),' times.']); end hObject is the handle of the edit text component because this code appears in the edit text callback.
9 Managing and Sharing Application Data in GUIDE 3 edit sliderbox_guidata or click here to open the GUI code file in the Editor. You can view the properties of any component by double-clicking it in the Layout Editor to open the Property Inspector for it. You can modify either the figure, the code, or both. Then you can save the GUI in your current folder using File > Save as from GUIDE. This saves both files, allowing you to rename them if you choose.
Ways to Manage Data in a GUIDE GUI • When a user types a value into the edit text component, the slider updates to this value. • If a user enters a value in the edit text that is out of range for the slider (a value that is not between 0 and 1), the application returns a message in the edit text component that indicates the number of times the user entered an incorrect value.
9 Managing and Sharing Application Data in GUIDE • The set command sets the String property of the edit text to the updated value. 3 Set the slider value from the edit text component’s callback. The edit text component’s callback sets the slider’s value to the number the user enters, after checking to see if it is a single numeric value between 0 and 1.
Making Multiple GUIs Work Together Making Multiple GUIs Work Together In this section... “Data-Sharing Techniques” on page 9-21 “Example — Manipulating a Modal Dialog Box for User Input” on page 9-22 “Example — Individual GUIDE GUIs Cooperating as Icon Manipulation Tools” on page 9-30 Data-Sharing Techniques Several of the techniques described in “Examples of Sharing Data Among a GUI’s Callbacks” on page 9-10 for sharing data within a GUI can also share data among several GUIs.
9 Managing and Sharing Application Data in GUIDE Example — Manipulating a Modal Dialog Box for User Input • “View and Run the changeme GUI” on page 9-23 • “Invoking the Text Change Dialog Box” on page 9-24 • “Managing the Text Change Dialog” on page 9-25 • “Protecting and Positioning the Text Change Dialog” on page 9-26 • “Initializing Text in the Text Change Dialog Box” on page 9-28 • “Canceling the Text Change Dialog Box” on page 9-28 • “Applying the Text Change” on page 9-29 • “Closing the Main GUI” on
Making Multiple GUIs Work Together Note The changeme_dialog GUI is patterned after the MATLAB inputdlg function, a predefined dialog box that serves the same purpose. It also calls uiwait to block the calling GUI and other processes. You can use inputdlg when creating programmatic GUIs. View and Run the changeme GUI If you are reading this in the MATLAB Help browser, you can access the example FIG-files and code files by clicking the following links.
9 Managing and Sharing Application Data in GUIDE You can view the properties of any component by double-clicking it in the Layout Editor to open the Property Inspector for it. You can modify either the figure, the code, or both. Then you can save the GUI in your current folder using File > Save As from GUIDE. This saves both the GUI and its code file. If you save one of the GUIs in this way, you need to save the other one as well.
Making Multiple GUIs Work Together changeme_dialog('changeme_main', handles.figure); The dialog box uses the handle to access the main GUI’s data. If the main GUI’s data is missing, the dialog box displays an error in the Command Window that describes proper usage and then exits. Managing the Text Change Dialog 1 In the Property Inspector for the Text Change dialog box’s figure, set the WindowStyle property to 'Modal'.
9 Managing and Sharing Application Data in GUIDE . . . uiresume(handles.figure); Protecting and Positioning the Text Change Dialog 1 The user opens the Text Change dialog box by triggereing the main GUI’s buttonChangeMe_Callback callback, which supplies the main GUI’s figure handle as a property called changeme_main. 2 The OpeningFcn for the dialog box validates the input by searching and indexing into the varagin cell array.
Making Multiple GUIs Work Together disp('-----------------------------------------------------'); disp('Improper input arguments. Pass a property value pair') disp('whose name is "changeme_main" and value is the handle') disp('to the changeme_main figure.
9 Managing and Sharing Application Data in GUIDE set(hObject, 'Position', [newX, newY, newW, newH]); . . . Initializing Text in the Text Change Dialog Box 1 To initialize the Text Change dialog box text to the Change Me button’s current text, get the main GUI’s handles structure from its handle, passed to the modal dialog box: function changeme_dialog_OpeningFcn(hObject, ... eventdata, handles, varargin) mainGuiInput = find(strcmp(varargin, 'changeme_main')); . . . handles.
Making Multiple GUIs Work Together uiresume(handles.figure); function figure_CloseRequestFcn(hObject, ... eventdata, handles) uiresume(hObject); Applying the Text Change Use the reference to the main GUI in the handles structure saved by OpeningFcn in the modal dialog box to apply the text change. The user clicks OK to apply the text change. This sets the Change Me button label in the main GUI to the value entered in the text field of the modal dialog box. function buttonOK_Callback(hObject, ...
9 Managing and Sharing Application Data in GUIDE wait state; if it is, it calls uiresume and returns, enabling the OutputFcn to be called: function figure_CloseRequestFcn(hObject,eventdata,handles) % hObject handle to figure (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Check appdata flag to see if the main GUI is in a wait state if getappdata(handles.
Making Multiple GUIs Work Together These GUIs share data and expose functionality to one another using several different techniques: 9-31
9 Managing and Sharing Application Data in GUIDE View and Run the Three Icon Manipulation GUIs If you are reading this in the MATLAB Help browser, you can access the example FIG-files and code files by clicking the following links. If you are reading this on the Web or in PDF form, you should go to the corresponding section in the MATLAB Help Browser to use the links.
Making Multiple GUIs Work Together Note Do not save GUI files to the examples folder where you found them, or you will overwrite the original files. If you want to save the GUI files, use File > Save as from GUIDE, which saves both the GUI FIG-file and the GUI code file.
9 Managing and Sharing Application Data in GUIDE guide_iconeditor_OpeningFcn(hObject, eventdata, handles, varargin) varargout = guide_iconeditor_OutputFcn(hObject, eventdata, handles) editFilename_CreateFcn(hObject, eventdata, handles) buttonImport_Callback(hObject, eventdata, handles) buttonOK_Callback(hObject, eventdata, handles buttonCancel_Callback(hObject, eventdata, handles) editFilename_ButtonDownFcn(hObject, eventdata, handles) editFilename_Callback(hObject, eventdata, handles) figure_CloseRequest
Making Multiple GUIs Work Together toolPicker_CreateFcn(hObject, eventdata, handles) toolPalette_SelectionChangeFcn(hObject, eventdata, handles) figure_CloseRequestFcn(hObject, eventdata, handles) [iconEditor, iconEditorHandles] = getIconEditor(handles) cdata = pencilToolCallback(handles, toolstruct, cdata, point) cdata = eraserToolCallback(handles, toolstruct, cdata, point) cdata = bucketToolCallback(handles, toolstruct, cdata, point) cdata = fillWithColor(cdata, rows, cols, color, row, col, seedcolor) cd
9 Managing and Sharing Application Data in GUIDE . . . % Update handles structure guidata(hObject, handles); The Color Palette needs to remember the Icon Editor for later: % in colorPalette function guide_colorpalette_OpeningFcn(hObject,eventdata,handles,varargin) handles.output = hObject; . . . handles.iconEditor = []; iconEditorInput = find(strcmp(varargin, 'iconEditor')); if ~isempty(iconEditorInput) handles.iconEditor = varargin{iconEditorInput+1}; end . . .
Making Multiple GUIs Work Together . . . % Update handles structure guidata(hObject, handles); Setting the Initial Color on the Color Palette After you create all three GUIs, you need to set the initial color. When you invoke the Color Palette from the Icon Editor, the Color Palette passes a function handle that tells the Icon Editor how to set the initial color. This function handle is stored in its handles structure.
9 Managing and Sharing Application Data in GUIDE handles.mSelectedColor =color; . . . guidata(hObject, handles); Call the publicized function from the Icon Editor, setting the initial color to 'red': % in Icon Editor function guide_iconeditor_OpeningFcn(hObject, ... eventdata, handles, varargin) . . . handles.colorPalette = guide_colorpalette('iconEditor', hObject); . . . colorPalette = handles.colorPalette; colorPaletteHandles = guidata(colorPalette); colorPaletteHandles.
Making Multiple GUIs Work Together . . % Update handles structure guidata(hObject, handles); The Icon Editor retrieves the initial color from the Color Palette’s GUI data via its handles structure: % in Icon Editor function color = getColor(hObject) handles = guidata(hObject); colorPalette = handles.colorPalette; colorPaletteHandles = guidata(colorPalette); color = colorPaletteHandles.
9 Managing and Sharing Application Data in GUIDE guidata(hObject, handles); When you select the pencil tool and click in the icon-editing area, the Icon Editor calls the pencil tool function: % in iconEditor function iconEditor_WindowButtonDownFcn(hObject,... eventdata, handles) toolPalette = handles.toolPalette; toolPaletteHandles = guidata(toolPalette); . . . userData = get(toolPaletteHandles.mCurrentTool, 'UserData'); handles.mIconCData = userData.Callback(toolPaletteHandles, ... toolPaletteHandles.
Making Multiple GUIs Work Together . . . rows = size(handles.mIconCData,1); cols = size(handles.mIconCData,2); pt = get(handles.icon,'currentpoint'); overicon = (pt(1,1)>=0 && pt(1,1)<=rows) && ... (pt(1,2)>=0 && pt(1,2)<=cols); . . . if ~overicon set(hObject,'pointer','arrow'); else toolPalette = handles.toolPalette; toolPaletteHandles = guidata(toolPalette); tool = toolPaletteHandles.
9 Managing and Sharing Application Data in GUIDE You cannot close the Color Palette and Tool Palette windows by directly clicking their close button (X). In the next example, you set the output of Icon Editor to be the CData of the icon. The opening function for Icon Editor, with uiwait, contains this code: % in Icon Editor function guide_iconeditor_OpeningFcn(hObject, eventdata, ... handles, varargin) . . . handles.colorPalette = guide_colorpalette(); handles.
Making Multiple GUIs Work Together function figure_CloseRequestFcn(hObject, eventdata, handles) % Don't close this figure. It must be deleted from Icon Editor Do the same for the Tool Palette: % in toolPalette function figure_CloseRequestFcn(hObject, eventdata, handles) % Don't close this figure. It must be deleted from Icon Editor Finally, in the output function, delete all three GUIs: % in Icon Editor function varargout = guide_iconeditor_OutputFcn(hObject, ...
9 9-44 Managing and Sharing Application Data in GUIDE
10 Examples of GUIDE GUIs • “GUI with Multiple Axes (GUIDE)” on page 10-2 • “GUI for Animating a 3-D View (GUIDE)” on page 10-15 • “GUI to Interactively Explore Data in a Table (GUIDE)” on page 10-31 • “List Box Directory Reader (GUIDE)” on page 10-54 • “Access Workspace Variables from a List Box (GUIDE)” on page 10-61 • “A GUI to Set Simulink Model Parameters (GUIDE)” on page 10-66 • “An Address Book Reader (GUIDE)” on page 10-81 • “Use a Modal Dialog Box to Confirm an Operation (GUIDE)” on page 10-98 • “T
10 Examples of GUIDE GUIs GUI with Multiple Axes (GUIDE) In this section... “About the Multiple Axes Example” on page 10-2 “View and Run the Multiple Axes GUI” on page 10-3 “Design the Multiple Axes GUI” on page 10-4 “Plot Push Button Callback” on page 10-8 “Validate User Input as Numbers” on page 10-11 About the Multiple Axes Example This example creates a GUI that plots data that it derives from three parameters entered by the user. The parameters define a time- and frequency-varying signal.
GUI with Multiple Axes (GUIDE) Note You can create a more advanced GUI that also displays time and frequency plots by following the GUIDE example “GUI to Interactively Explore Data in a Table (GUIDE)” on page 10-31. View and Run the Multiple Axes GUI If you are reading this in the MATLAB Help browser, you can access the example FIG-file and code file by clicking the following links.
10 Examples of GUIDE GUIs 1 Click here to copy the files to your current folder. 2 Type guide two_axes or click here to open the GUI in GUIDE. 3 Type edit two_axes or click here to open the GUI code file in the Editor. You can view the properties of any component by double-clicking the component in the Layout Editor to open the Property Inspector for it. You can modify either the figure, the code, or both. Then you can save the GUI in your current folder using File > Save as from GUIDE.
GUI with Multiple Axes (GUIDE) • Frequency two (f2) • A time vector (t) When the user clicks the Plot button, the GUI puts these values into a MATLAB expression that is the sum of two sine functions: x = sin(2*pi*f1*t) + sin(2*pi*f2*t) The GUI then calculates the FFT (fast Fourier transform) of x and plots the data in the frequency domain and the time domain in separate axes. Specify Default Values for the Inputs The GUI provides default values for the three inputs.
10 Examples of GUIDE GUIs To create the default values, set the String property of the edit text. The following figure shows the value set for the time vector. Identify the Axes Since there are two axes in this GUI, you must specify which one you want to target when plotting data. Use the handles structure, which contains the handles of all components in the GUI, to identify that axes.
GUI with Multiple Axes (GUIDE) The structure contains handles for all GUI components. You access the handles using field names that GUIDE derives from the components’ Tag property. To make code more readable (and to make it easier to remember) this example sets the Tag property to descriptive names. The following graphic shows how to set the upper axes Tag to 'frequency_axes' in the Property Inspector.
10 Examples of GUIDE GUIs GUI Option Settings GUIDE has a set of preferences called GUI Options, available from the Tools menu. Two GUI Options settings are particularly important for this GUI: • Resize behavior: Proportional • Command-line accessibility: Callback Proportional Resize Behavior. Selecting Proportional as the resize behavior enables users to resize the GUI to better view the plots. Using this option setting, when you resize the GUI, everything expands or shrinks proportionately except text.
GUI with Multiple Axes (GUIDE) • Evaluating the time string using eval to produce a vector t, which the callback used to evaluate the mathematical expression. The following code shows how the callback obtains the input: % Get user input from GUI f1 = str2double(get(handles.f1_input,'String')); f2 = str2double(get(handles.f2_input,'String')); t = eval(get(handles.t_input,'String')); The Plot button callback avoid generating errors due to receiving improper inputs.
10 Examples of GUIDE GUIs • Providing the appropriate data to the plot function • Turning on the axes grid, which the plot function automatically turns off Performing the last step is necessary because many plotting functions (including plot) clear the axes and reset properties before creating the graph. This meansthat you cannot use the Property Inspector to set the XMinorTick, YMinorTick, and grid properties in this example, because they are reset when the callback executes plot.
GUI with Multiple Axes (GUIDE) Validate User Input as Numbers GUI users type parameters into three edit text boxes as strings of text. If they type an inappropriate number or something that is not a number, the graphs can fail to inform or even to generate. Preventing bad inputs from being processed is an important function of almost any GUI that performs computations. In this GUI, it is important that: • All three inputs are positive or negative real numbers.
10 Examples of GUIDE GUIs if isnan(f1) || ~isreal(f1) % isdouble returns NaN for non-numbers and f1 cannot be complex % Disable the Plot button and change its string to say why set(handles.plot_button,'String','Cannot plot f1') set(handles.plot_button,'Enable','off') % Give the edit text box focus so user can correct the error uicontrol(hObject) else % Enable the Plot button with its original name set(handles.plot_button,'String','Plot') set(handles.
GUI with Multiple Axes (GUIDE) % t is not a number set(handles.plot_button,'String','t is not numeric') elseif length(t) < 2 % t is not a vector set(handles.plot_button,'String','t must be vector') elseif length(t) > 1000 % t is too long a vector to plot clearly set(handles.plot_button,'String','t is too long') elseif min(diff(t)) < 0 % t is not monotonically increasing set(handles.plot_button,'String','t must increase') else % All OK; Enable the Plot button with its original name set(handles.
10 Examples of GUIDE GUIs In this figure, the two plots reflect the last successful set of inputs, f1 = 31.41, f2 = 120, and t = [1 2 3 4 5 7 9]. The time vector [1 2 6 4 5 7 9] appears highlighted so that the user can enter a new value. The highlighting results from executing the command uicontrol(hObject) in the above listing.
GUI for Animating a 3-D View (GUIDE) GUI for Animating a 3-D View (GUIDE) In this section... “About the 3-D Animation Example” on page 10-15 “View and Run the 3-D Globe GUI” on page 10-16 “Design the 3-D Globe GUI” on page 10-17 “Graphics Techniques Used in the 3-D Globe GUI” on page 10-24 “Further Graphic Explorations” on page 10-29 About the 3-D Animation Example This example GUI has 3-D axes in which the Earth spins on its axis.
10 Examples of GUIDE GUIs • Start and stop the rotation. • Change lighting direction. • Display a latitude-longitude grid (or graticule). • Save the animation as a movie in a MAT-file. • Exit the application. GUI-building techniques illustrated in this example include: • Changing the label (string) of a button every time it is clicked. • Storing data in the handles structure and using it to control callback execution. • Enabling a callback to interrupt its own execution.
GUI for Animating a 3-D View (GUIDE) the figure, the code, or both. Then you can save the GUI in your current folder using File > Save as from GUIDE. This saves both files, allowing you to rename them, if you choose. To just inspect the GUI in GUIDE and run it, follow these steps instead: 1 Click here to add the example files to the MATLAB path (only for the current session). 2 Click here to run the globegui GUI. 3 Click here to display the GUI in the GUIDE Layout Editor (read only).
10 Examples of GUIDE GUIs • Static text The Property Inspector was used to customize the uicontrols and text by: • Setting the figure Color to black, as well as the BackgroundColor, ForegroundColor, and ShadowColor of the three uipanels. (They are used as containers only, so they do not need to be visible.) • Coloring all static text yellow and uicontrol backgrounds either black or yellow-gray. • Giving all uicontrols mnemonic names in their Tag string. • Setting the FontSize for uicontrols to 9 points.
GUI for Animating a 3-D View (GUIDE) The GUI includes three uipanels that you can barely see in this figure because they are entirely black. Using uipanels helps the graphic functions work more efficiently. The axes CreateFcn (axes1_CreateFcn) initializes the graphic objects. It executes once, no matter how many times the GUI is opened. The Spin button’s callback (spinstopbutton_Callback), which contains a while loop for rotating the spherical surface, conducts the animation.
10 Examples of GUIDE GUIs The Show grid check box toggles the Visible property of the graticule surface object. The axes1_CreateFcn initializes the graticule and then hides it until the user selects this option. The Spin button’s callback reads the Make movie check box value to accumulate movie frames and saves the movie to a MAT-file when rotation is stopped or after one full revolution, whichever comes first. (The user must select Make movie before spinning the globe.
GUI for Animating a 3-D View (GUIDE) Function Function Behavior sunazslider_CreateFcn Initializes light source azimuth slider (not customized) sunelslider_Callback Changes elevation of light source as user moves slider sunelslider_CreateFcn Initializes light source elevation slider (not customized) showgridbutton_Callback Toggles the graticule grid visibility movie_checkbox_Callback Toggles capturing and saving a movie of the animation movie_checkbox_CreateFcn Initializes the movie button and
10 Examples of GUIDE GUIs str = get(hObject,'String'); state = find(strcmp(str,handles.Strings)); set(hObject,'String',handles.Strings{3-state}); The find function returns the index of the string that matches the button’s current label. The call to set switches the label to the alternative string. If state is 1, 3-state sets it to 2. If state is 2, it sets it to 1.
GUI for Animating a 3-D View (GUIDE) example does not explore the technique, but you can find information about programming timers in “Using a MATLAB Timer Object”. Make a Movie of the Animation Selecting the Make movie check box before clicking Spin causes the application to record each frame displayed in the while loop of the spinstopbutton_Callback routine. When the user selects this check box, the animation runs more slowly because the following block of code executes: filming = handles.movie; ...
10 Examples of GUIDE GUIs The file name of the movie ends with the number of frames it contains. Supposing the movie’s file name is globe360.mat, you play it with: load globe360 axis equal off movie(globeframes) The playback looks like this. To see the spinstopbutton_Callback code in globegui.m in the MATLAB Editor, click here.
GUI for Animating a 3-D View (GUIDE) • “Create the Graphic Objects” on page 10-25 • “Texture and Color the Globe” on page 10-26 • “Plot the Graticule” on page 10-26 • “Orient the Globe and Graticule” on page 10-27 • “Light the Globe and Shift the Light Source” on page 10-28 Create the Graphic Objects The axes1_CreateFcn function initializes the axes, the two objects displayed in it, and two hgtransform objects that affect the rotation of the globe: • The globe, a surfaceplot object, generated by a call to
10 Examples of GUIDE GUIs Texture and Color the Globe Code in the axes1_CreateFcn sets the CData for the globe to the 180-by-360 (one degree) topo terrain grid by setting its FaceColor property to 'texturemap'. You can use any image or grid to texture a surface. Specify surface properties as a struct containing one element per property that you must set, as follows: props.FaceColor= 'texture'; props.EdgeColor = 'none'; props.FaceLighting = 'gouraud'; props.Cdata = topo; props.
GUI for Animating a 3-D View (GUIDE) The state of the Show grid button is initially off, causing the graticule not to display. Show grid toggles the mesh object’s Visible property. As mentioned earlier, enlarging the graticule by 2 percent before plotting prevents the terrain surface from obscuring it. Orient the Globe and Graticule The globe and graticule rotate as if they were one object, under the control of a pair of hgtransform objects. Within the figure, the HG objects are set up in this hierarchy.
10 Examples of GUIDE GUIs set(hgrotate,'Matrix',makehgtform('zrotate',az)); drawnow % Refresh the screen Light the Globe and Shift the Light Source A light object illuminates the globe, initially from the left. Two sliders control the light’s position, which you can manipulate whether the globe is standing still or rotating. The light is a child of the axes, so is not affected by either of the hgtransforms.
GUI for Animating a 3-D View (GUIDE) Further Graphic Explorations You can enhance the presentation of globegui in various ways, including: • Adding a colorbar to show how colors correspond to terrain elevation above and below sea level You cannot use GUIDE to set up a colorbar, but you can do so in axes1_CreateFcn. For more information about using colorbars, see the reference page for colorbar and “Adding a Colorbar to a Graph”.
10 Examples of GUIDE GUIs Tip Use a spherical grid that is the same size as topo to add terrain relief to the globe. Then scale the values of topo to well under 1.0 and factor them into the x, y, and z matrices. The result might look something like this figure, in which terrain relief is scaled to add 10% to the globe’s radius, greatly exaggerating terrain relief.
GUI to Interactively Explore Data in a Table (GUIDE) GUI to Interactively Explore Data in a Table (GUIDE) In this section... “About the tablestat Example” on page 10-31 “View and Run the tablestat GUI” on page 10-33 “Design the tablestat GUI” on page 10-35 “Extend the tablestat GUI” on page 10-52 About the tablestat Example This example shows how to program callbacks for interactive data exploration, including: • An Opening Function to initialize a table and a plot.
10 Examples of GUIDE GUIs • Plots that portray periodicity in the entire data set and in selections of it. • Context menus for the axes that let the user display their contents in a separate figure window. Use this GUI—or one you adapt from it—to analyze and visualize time-series data containing periodic events. Besides the tables and axes, the GUI features three panels, a push button to quit the application, static text, and functions for analyzing and plotting data.
GUI to Interactively Explore Data in a Table (GUIDE) Note The tablestat example is based on the MATLAB sunspots demo and data set. Click here to view that demo (which is not GUI-based) in the MATLAB Help Browser. View and Run the tablestat GUI If you are reading this document in the MATLAB Help browser, you can access the example FIG-file and code file by clicking the following links.
10 Examples of GUIDE GUIs Note Do not save GUI files to the examples folder where you found them or you will overwrite the original files. If you want to save GUI files, use File > Save as from GUIDE, which saves both the GUI FIG-file and the GUI code file. Summary of tablestat Functions The following table describes all the functions in tablestat.m, indicates what they do, and whether GUIDE created declarations for them or not.
GUI to Interactively Explore Data in a Table (GUIDE) Function Name Function Behavior GUIDEGenerated? plotPeriod Generates plots (either time series or periodogram) No quit_Callback Closes the figure Yes Design the tablestat GUI • “Initialize the Data Table” on page 10-40 • “Compute the Data Statistics” on page 10-41 • “Specify the Type of Data Plot” on page 10-42 • “Respond to Data Selections” on page 10-44 • “Update the Statistics Table and the Graphs” on page 10-46 • “Display Graphs in New Figur
10 Examples of GUIDE GUIs Perform the following steps in GUIDE and in the Property Inspector to generate the layout, thereby creating the following objects: 1 Using the Panel tool , drag out the three uipanels in the positions that are shown above. Keep the defaults for their Tag properties (which are uipanel1, uipanel2, and uipanel3). Create, in order: • A long panel on the left, renaming its Title to Data Set in the Property Inspector.
GUI to Interactively Explore Data in a Table (GUIDE) • A panel on the lower right, half the height of the first panel, renaming its Title to Data Statistics in the Property Inspector. • A panel above the Data Statistics panel, renaming its Title to Sunspots v. Year Plots in the Property Inspector. This panel changes its name when the type of plot that is displayed changes.
10 Examples of GUIDE GUIs b In the Property Inspector, click the Table Property Editor icon to the right of the RowName property to open the Table Property Editor. c In the Table Property Editor, select Rows from the list in the left-hand column. d Select the bottom radio button, Show names entered below as row headers. e Type the nine strings listed above in order on separate lines in the data entry pane and click OK. The Table Property Editor looks like this before you close it.
GUI to Interactively Explore Data in a Table (GUIDE) 5 Drag out a second axes, leaving its name as axes2 inside the Sunspots v. Year Plots panel, directly below the first axes. Leave enough space below each axes to display the x-axis labels. 6 Identify the axes with labels. Using the Text tool, drag out a small rectangle in the upper right corner of the upper axes (axes1). Double-click it, and in the Property Inspector, change its String property to Population and its Tag property to poplabel.
10 Examples of GUIDE GUIs • Double-click it and in the Property Inspector, set its Tag property to quit and its String property to Quit. • Click the Callback property to create a callback for the button in the code file tablestat.m. GUIDE sets the Callback of the Quit item to quit_Callback. • In the code file, for the quit_Callback function. enter: close(ancestor(hObject,'figure')) . 12 Save the GUI in GUIDE, naming it tablestat.fig. This action also saves the code file as tablestat.m.
GUI to Interactively Explore Data in a Table (GUIDE) 6 From the list of workspace variables in the box below the radio button, select sunspot and click OK. GUIDE inserts the sunspot data in the table. Note If you are designing a GUI like this but need to allow your users to load their own numeric data in place of the sunspot data, you need a way to interrogate the MATLAB workspace and present a list of variables to the user.
10 Examples of GUIDE GUIs if ~isempty(peak) stats{9,col} = peak; end % Peak period from FFT Note When assigning data to a uitable, use a cell array, as shown in the code for setStats. You can assign data that you retrieve from a uitable to a numeric array, however, only if it is entirely numeric. Storing uitable data in cell arrays enables tables to hold numbers, strings of characters, or combinations of them.
GUI to Interactively Explore Data in a Table (GUIDE) function plot_type_Callback(hObject, eventdata, handles) % hObject handle to plot_type (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % ---- Customized as follows ---% Determine state of the pop-up and assign the appropriate string % to the plot panel label index = get(hObject,'Value'); % What plot type is requested? strlist = get(hObject,'String'); % Get the choi
10 Examples of GUIDE GUIs Respond to Data Selections The Data Set table has two columns: Year and Sunspots. The data tables’s Cell Selection Callback analyzes data from its second column, regardless of which columns the user highlights. The setStats function (not generated by GUIDE) computes summary statistics observations from the second column for insertion into the Data Statistics table on the right.
GUI to Interactively Explore Data in a Table (GUIDE) discontiguous rows to a selection. Because the Cell Selection Callback is triggered as long as the user holds the left mouse button down within the table, the selection statistics and lower plot are refreshed until selection is completed. Selection data is generated during mouseDown events (mouse drags in the data table).
10 Examples of GUIDE GUIs This vector enumerates all the selected rows. If the selection includes less than 11 rows (as it does here) the callback returns, because computing statistics for a sample that small is not useful.
GUI to Interactively Explore Data in a Table (GUIDE) updates the Data Statistics table with the recomputed statistics. Here is the code for refreshDisplays: function refreshDisplays(table, handles, item) if isequal(item,1) ax = handles.axes1; elseif isequal(item,2) ax = handles.axes2; end peak = plotPeriod(ax, table,... get(handles.plot_type,'Value')); stats = get(handles.data_stats, 'Data'); stats = setStats(table, stats, item, peak); set(handles.
10 Examples of GUIDE GUIs 3 Resizing the new axes to use 90% of the figure’s width. 4 Constructing a title string and displaying it in the new figure. 5 Saving the figure and axes handles in the handles structure for possible later use or destruction. Note Handles are saved for both plots, but each time a new figure is created for either of them, the new handles replace the old ones, if any, making previous figures inaccessible from the GUI. Create Two Context Menus.
GUI to Interactively Explore Data in a Table (GUIDE) 7 Click OK to save your menus and exit the Menu Editor. For more information about using the Menu Editor, see “Create Menus in a GUIDE GUI” on page 6-101. Attach Context Menus to Axes. Add the context menus you just created to the axes: 1 In the GUIDE Layout Editor, double-click axes1 (the top axes in the upper right corner) to open it in the Property Inspector. 2 Click the right-hand column next to UIContextMenu to see a drop-down list.
10 Examples of GUIDE GUIs % we want to do anything else to them handles.axes1fig = axes1fig; handles.axes1copy = axes1copy; guidata(hObject,handles); The other callback, plot_ax2_Callback, is identical to plot_ax1_Callback, except that all instances of 1 in the code are replaced by 2, and poplabel is replaced with sellabel. The poplabel and sellabel objects are the Population and Selection labels on axes1 and axes2, respectively.
GUI to Interactively Explore Data in a Table (GUIDE) Upon Clicking Open plot in new window, a new figure is displayed with the following content.
10 Examples of GUIDE GUIs It is the user’s responsibility to remove the new window when it is no longer needed. The context menus can be programmed to do this. Because their callbacks call guidata to save the handle of the last figure created for each of the GUI’s axes, another callback can delete or reuse either figure. For example, the plot_ax1_Callback and plot_ax2_Callback callbacks could check guidata for a valid axes handle stored in handles.axes1copy or handles.
GUI to Interactively Explore Data in a Table (GUIDE) - Provide a file dialog box or an input dialog box and code capable of filtering out nonnumeric, nonmatrix data. - Provide default names for columns and a way for the user to rename them. • Enable the user to select which data columns to analyze and plot: - A way for the user to indicate which columns to use as independent (x, normally) and dependent (y, normally) variables.
10 Examples of GUIDE GUIs List Box Directory Reader (GUIDE) In this section... “About the List Box Directory Example” on page 10-54 “View and Run the List Box Directory GUI” on page 10-55 “Implement the List Box Directory GUI” on page 10-56 About the List Box Directory Example This example uses a list box to display the files in a folder. When the user double clicks a list item, one of the following happens: • If the item is a file, the GUI opens the file appropriately for the file type.
List Box Directory Reader (GUIDE) View and Run the List Box Directory GUI If you are reading this document in the MATLAB Help browser, you can access the example FIG-file and code file by clicking the following links. If you are reading this on the Web or in PDF form, go to the corresponding section in the MATLAB Help Browser to use the links.
10 Examples of GUIDE GUIs Note Do not save GUI files to the examples folder where you found them or you will overwrite the original files. If you want to save GUI files, use File > Save as from GUIDE, which saves both the GUI FIG-file and the GUI code file. Implement the List Box Directory GUI The following sections describe the implementation: • “Specify the Directory” on page 10-56 — shows how to pass a folder path as input argument when the GUI runs.
List Box Directory Reader (GUIDE) % 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) % Choose default command line output for lbox2 handles.
10 Examples of GUIDE GUIs • Use the dir command to get a list of files in the specified folder and to determine which name is a folder and which is a file. dir returns a structure (dir_struct) with two fields, name and isdir, which contain this information. • Sort the file and folder names (sortrows) and save the sorted names and other information in the handles structure so that this information can be passed to other functions.
List Box Directory Reader (GUIDE) is a file, it is passed to the open command; if it is a folder, the GUI changes to that folder and lists its contents. Define How to Open File Types. The open command can handle a number of different file types, however, the callback treats FIG-files differently. Instead of opening the FIG-file as a standalone figure, it opens it with guide for editing. Determine Which Item the User Selected.
10 Examples of GUIDE GUIs file_list = get(handles.listbox1,'String'); % Item selected in list box filename = file_list{index_selected}; % If folder if handles.is_dir(handles.sorted_index(index_selected)) cd (filename) % Load list box with new folder. load_listbox(pwd,handles) else [path,name,ext] = fileparts(filename); switch ext case '.fig' % Open FIG-file with guide command. guide (filename) otherwise try % Use open for other file types. open(filename) catch ex errordlg(... ex.
Access Workspace Variables from a List Box (GUIDE) Access Workspace Variables from a List Box (GUIDE) In this section... “About the Workspace Variable Example” on page 10-61 “View and Run the Workspace Variable GUI” on page 10-62 “Read Workspace Variables” on page 10-63 “Read Selections from List Box” on page 10-64 About the Workspace Variable Example This GUI uses a list box to display names of and plot variables in the base workspace. Initially, no variable names are selected in the list box.
10 Examples of GUIDE GUIs View and Run the Workspace Variable GUI If you are reading this document in the MATLAB Help browser, you can access the example FIG-file and code file by clicking the following links. If you are reading this on the Web or in PDF form, go to the corresponding section in the MATLAB Help Browser to use the links.
Access Workspace Variables from a List Box (GUIDE) To just inspect the GUI in GUIDE and run it, follow these steps instead: 1 Click here to add the example files to the MATLAB path (only for the current session). 2 Click here to run the lb GUI. 3 Click here to display the GUI in the GUIDE Layout Editor (read only). 4 Click here to display the GUI code file in the MATLAB Editor (read only). Note Do not save GUI files to the examples folder where you found them or you will overwrite the original files.
10 Examples of GUIDE GUIs Read Selections from List Box The 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. No callback for the list box exists in the GUI code file. One is not needed because the plotting actions are initiated by push buttons. Enable Multiple Selection To enable multiple selection in a list box, you must set the Min and Max properties so that Max - Min > 1.
Access Workspace Variables from a List Box (GUIDE) list_entries = get(handles.listbox1,'String'); index_selected = get(handles.listbox1,'Value'); if length(index_selected) ~= 2 errordlg('You must select two variables',...
10 Examples of GUIDE GUIs A GUI to Set Simulink Model Parameters (GUIDE) In this section...
A GUI to Set Simulink® Model Parameters (GUIDE) The example illustrates a number of GUI building techniques: • Opening and setting parameters on a Simulink model from a GUI. • Implementing sliders that operate in conjunction with text boxes, which display the current value, as well as accepting user input. • Enabling and disabling controls, depending on the state of the GUI. • Managing a variety of shared data using the handles structure. • Directing graphics output to figures with hidden handles.
10 Examples of GUIDE GUIs 2 Type guide f14ex or click here to open the FIG-file in GUIDE. 3 Type edit f14ex or click here to open the code file in the Editor. You can view the properties of any component by double-clicking it in the Layout Editor to open the Property Inspector for it. You can modify either the figure, the code, or both, and then save the GUI in your current folder using File > Save as from GUIDE. This saves both files, allowing you to rename them, if you choose.
A GUI to Set Simulink® Model Parameters (GUIDE) F14 Controller Gain Editor You can use the F14 Controller Gain Editor to analyze how changing the gains used in the Proportional-Integral Controller affect the aircraft’s angle of attack and the amount of G force the pilot feels. Note that the Simulink diagram f14.mdl must be open to run this GUI. If you close the F14 Simulink model, the GUI reopens it whenever it requires the model to execute.
10 Examples of GUIDE GUIs 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. Remove Results To remove a result from the Results list, select the row or rows you want to remove and click the Remove button. Run the GUI The GUI is nonblocking and nonmodal because it is designed to be used as an analysis tool.
A GUI to Set Simulink® Model Parameters (GUIDE) • 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: function model_open(handles) if isempty(find_system('Name','f14')), open_system('f14'); open_system('f14/Controller') set_param('f14/Controller/Gain','Position',[275 14 340 56]) figure(handles.F14ControllerEditor) set_param('f14/Controller Gain','Gain',...
10 Examples of GUIDE GUIs • 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 KfValueSlider_Callback(hObject, eventdata, handles) % Ensure model is open. model_open(handles) % Get the new value for the Kf Gain from the slider. NewVal = get(hObject, 'Value'); % Set the value of the KfCurrentValue to the new value % set by slider. set(handles.
A GUI to Set Simulink® Model Parameters (GUIDE) If the value is in range, the slider Value property is updated to the new value. • Sets the appropriate block parameter to the new value (set_param). Here is the callback for the Kf Current value text box: function KfCurrentValue_Callback(hObject, eventdata, handles) % Ensure model is open. model_open(handles) % Get the new value for the Kf Gain.
10 Examples of GUIDE GUIs • Creates a structure to save the results of the simulation, the current values of the simulation parameters set by the GUI, and the run name and number. • Stores the structure in the handles structure. • Updates the list box String to list the most recent run.
A GUI to Set Simulink® Model Parameters (GUIDE) if isequal(ResultNum,1) ResultsStr = {['Run1',num2str(Kf),' ',num2str(Ki)]}; else ResultsStr = [ResultsStr;... {['Run',num2str(ResultNum),' ',num2str(Kf),' ', ... num2str(Ki)]}]; end set(handles.ResultsList,'String',ResultsStr); % Store the new ResultsData handles.ResultsData = ResultsData; guidata(hObject, handles) Remove Results from List Box The GUI Remove button callback deletes any selected item from the Results list list box.
10 Examples of GUIDE GUIs if isequal(numResults,length(currentVal)), resultsStr = {''}; currentVal = 1; set([handles.RemoveButton,handles.PlotButton],'Enable','off') end % Ensure that list box Value is valid, then reset Value and String currentVal = min(currentVal,size(resultsStr,1)); set(handles.ResultsList,'Value',currentVal,'String',resultsStr) % Store the new ResultsData guidata(hObject, handles) Plot Results Data The GUI Plot button callback creates a plot of the run data and adds a legend.
A GUI to Set Simulink® Model Parameters (GUIDE) • Create an axes, set its Parent property to the figure handle, and save the axes handle. • Create the plot (which is one or more line objects), save these line handles, and set their Parent properties to the handle of the axes. • Make the figure visible. Plot Button Callback Listing Here is the Plot button callback. function PlotButton_Callback(hObject, eventdata, handles) currentVal = get(handles.
10 Examples of GUIDE GUIs end % Plot data pHandles = plot(PlotData{:},'Parent',handles.PlotAxes); % Add a legend, and bring figure to the front legend(pHandles(1:2:end),legendStr{:}) % Make the figure visible and bring it forward figure(handles.PlotFigure) The GUI Help Button The GUI Help button callback displays an HTML file in the MATLAB Help browser.
A GUI to Set Simulink® Model Parameters (GUIDE) function CloseButton_Callback(hObject, eventdata, handles) % Close the GUI and any plot window that is open if isfield(handles,'PlotFigure') && ... ishandle(handles.PlotFigure), close(handles.PlotFigure); end close(handles.F14ControllerEditor); The List Box Callback and Create Function This GUI does not use the list box callback because the actions performed on list box items are carried out by push buttons (Simulate and store results, Remove, and Plot).
10 Examples of GUIDE GUIs Set the Background to White The list box create function enables you to determine the background color of the list box. The following code shows the create function for the list box that is tagged ResultsList: function ResultsList_CreateFcn(hObject, eventdata, handles) % Hint: listbox controls usually have a white background, change % 'usewhitebg' to 0 to use default. See ISPC and COMPUTER.
An Address Book Reader (GUIDE) An Address Book Reader (GUIDE) In this section...
10 Examples of GUIDE GUIs The example demonstrates the following GUI programming techniques: • Uses open and save dialog boxes 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. • Uses the GUI’s handles structure to save and recall shared data. • Uses a GUI figure resize function.
An Address Book Reader (GUIDE) 1 Click here to copy the files to your current folder. 2 Type guide address_book or click here to open the FIG-file in GUIDE. 3 Type edit address_book or click here to open the code file in the Editor. You can view the properties of any component by double-clicking it in the Layout Editor to open the Property Inspector for it. You can modify either the figure, the code, or both, and then save the GUI in your current folder using File > Save as from GUIDE.
10 Examples of GUIDE GUIs • Command-line accessibility: Off • GUI Options selected: - Generate callback function prototypes Application allows only one instance to run Call the GUI You can invoke the GUI 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').
An Address Book Reader (GUIDE) % Load the default address book Check_And_Load([],handles); % If the first element in varargin is 'book' and & the second element is a MATLAB file, then load that file 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.
10 Examples of GUIDE GUIs • Returns 1 for valid MAT-files and 0 if invalid (used by the Open menu callback). • Saves the following items in the handles structure: - The name of the MAT-file. The Addresses structure. An index pointer indicating which name and phone number are currently displayed 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.
An Address Book Reader (GUIDE) end % If the file is valid, display it if pass % Add Addresses to the handles structure handles.Addresses = data.Addresses; guidata(handles.Address_Book,handles) % Display the first entry set(handles.Contact_Name,'String',data.Addresses(1).Name) set(handles.Contact_Phone,'String',data.Addresses(1).Phone) % Set the index pointer to 1 and save handles handles.Index = 1; guidata(handles.
10 Examples of GUIDE GUIs File = fullfile(pathname,filename); % if the MAT-file is not valid, do not save the name if Check_And_Load(File,handles) handles.LastFIle = File; guidata(hObject, handles) end end Ffor information on creating the menu, see “Create Menus in a GUIDE GUI” on page 6-101. The Contact Name Callback The Contact Name text box displays the name of the address book entry.
An Address Book Reader (GUIDE) Contact Name Callback function Contact_Name_Callback(hObject, eventdata, handles) % Get the strings in the Contact Name and Phone text box Current_Name = get(handles.Contact_Name,'string'); Current_Phone = get(handles.Contact_Phone,'string'); % If empty then return if isempty(Current_Name) return end % Get the current list of addresses from the handles structure Addresses = handles.
10 Examples of GUIDE GUIs ) set(handles.Contact_Phone,'String',Addresses(handles.Index).Pho ne) return end The Contact Phone Number Callback The Contact Phone # text box displays the phone number of the entry listed in the Contact Name text box. If you type in a new number and click one of the push buttons, the callback opens a question dialog box that asks you if you want to change the existing number or cancel your change. Like the Contact Name text box, this callback uses the index pointer (handles.
An Address Book Reader (GUIDE) handles.Addresses = Addresses; guidata(hObject, handles) return case 'Cancel' % Revert back to the original number set(handles.Contact_Phone,... 'String',Addresses(handles.Index).Phone) return end Page Through Address Book — Prev/Next By clicking the Prev and Next buttons you can page back and forth through the entries in the address book. Both push buttons use the same callback, Prev_Next_Callback.
10 Examples of GUIDE GUIs is used in case statements to implement each button’s functionality (see the code listing that follows). 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 clicks, the index pointer is decremented or incremented and the corresponding address and phone number are displayed.
An Address Book Reader (GUIDE) Current_Phone = Addresses(i).Phone; 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(hObject, handles) Save Address Book Changes 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.
10 Examples of GUIDE GUIs Save_Callback Code Listing function Save_Callback(hObject, eventdata, handles) % Get the Tag of the menu selected Tag = get(hObject, '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';'*.*'}, .
An Address Book Reader (GUIDE) The Address Book Resize Function The address book defines its own resize function. To use this resize function, you must set the Application Options dialog box 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 software calls the ResizeFcn subfunction in the address book code file (address_book.
10 Examples of GUIDE GUIs Change the Height The height and width of the figure is specified in pixel units. Using units of pixels enables maximizing and minimizing the figure to work properly. The code assumes that its dimensions are 470-by-250 pixels. If the user attempts to change the height, the code restores the original height.
An Address Book Reader (GUIDE) return end % If resized figure is smaller than original figure then compensate % However, do not change figure size if it is docked; just adjust % uicontrols if ~strcmp(get(hObject,'WindowStyle'),'docked') 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) ...
10 Examples of GUIDE GUIs Use a Modal Dialog Box to Confirm an Operation (GUIDE) In this section...
Use a Modal Dialog Box to Confirm an Operation (GUIDE) figure property WindowStyle determines whether it is modal or not. Typing Ctrl+C changes a 'modal' WindowStyle to the default value, 'normal'. Modal figures stack on top of all existing figure windows, making them inaccessible as long as the top figure exists and remains modal.
10 Examples of GUIDE GUIs 2 Click here to run the modal GUIs. 3 Click here to display the GUIs in the GUIDE Layout Editor (read only). 4 Click here to display the GUI code files in the MATLAB Editor (read only). Note Do not save GUI files to the examples folder where you found them or you will overwrite the original files. If you want to save GUI files, use File > Save as from GUIDE, which saves both the GUI FIG-file and the GUI code file.
Use a Modal Dialog Box to Confirm an Operation (GUIDE) The GUI looks like the following figure. Note Modal dialog boxes (figures with WindowStyle set to 'modal') cannot display menus or toolbars. Set Up the GUI with the Close Button To set up the GUI with a Close button: 1 From the File menu in the GUIDE Layout Editor, select New. 2 In the GUIDE Quick Start dialog box, select Blank GUI (Default) and click OK. This opens the blank GUI in a new Layout Editor window.
10 Examples of GUIDE GUIs 8 Click the Show functions icon on the toolbar of the editor and select close_pushbutton_Callback from the drop-down menu. The following generated code for the Close button callback appears in the editor: % --- Executes on button press in close_pushbutton.
Use a Modal Dialog Box to Confirm an Operation (GUIDE) When you click the Close button on the GUI, the modal dialog box opens, as shown in the following figure. 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 Close-Confirmation GUIs Work This section describes what occurs when you click the Close button on the GUI: 1 User clicks the Close button.
10 Examples of GUIDE GUIs This is an example of calling a GUI with a property value pair. In this case, the figure property is 'Title', and its value is the string 'Confirm Close'. Opening modaldlg with this syntax displays the text “Confirm Close” at the top of the dialog box. 2 The modal dialog box opens with the 'Position' obtained from the GUI that calls it. 3 The opening function in the modal modaldlg code file: • Makes the dialog modal.
Time Data Updates from a GUI (GUIDE) Time Data Updates from a GUI (GUIDE) In this section... “About the Timer GUI Example” on page 10-105 “View and Run the GUIDE Timer GUI” on page 10-106 “Components Used by the Timer GUI” on page 10-107 “How the GUI Implements the Timer” on page 10-109 “Other Uses for Timers in GUIs” on page 10-112 About the Timer GUI Example This example shows how to refresh a display by incorporating a timer in a GUI that updates data. Timers are MATLAB objects.
10 Examples of GUIDE GUIs View and Run the GUIDE Timer GUI This example contains links to a FIG-file and a code file that MATLAB documentation provides. If you use the MATLAB Help browser to view the example, the links will be active and you can access the files. If you are reading this example on the Web or in PDF form, find this topic in the MATLAB Help Browser to use the links. To modify the layout or code of this GUI example, first save copies of its code file and FIG-file to your current folder.
Time Data Updates from a GUI (GUIDE) 2 Type guide ex_guide_timergui in the Command Window or click here to open the GUI in GUIDE. 3 Open the GUI code file, ex_guide_timergui.m, from GUIDE or click here to open the GUI code file in the Editor. You can view the properties of any component by double-clicking the component in the Layout Editor, which opens the Property Inspector for it. You can modify the figure, the code, or both. Then you can save the GUI in your current folder using File > Save as.
10 Examples of GUIDE GUIs the link in the Callback column. You cannot access the timer object from within GUIDE; it is created programmatically. Component Tag Description Callback push button startbtn Starts/resumes timer that adds noise to the surface plot, startbtn_ Callback push button stopbtn Halts timer to stop plot from updating. stopbtn_ Callback axes display Displays a changing surface plot. n/a slider periodsldr Changes period of timer between its Min of 0.01 s.
Time Data Updates from a GUI (GUIDE) How the GUI Implements the Timer Each callback in the GUI either creates, modifies, starts, stops, or destroys the timer object. The following sections describe what the callbacks do.
10 Examples of GUIDE GUIs startbtn_Callback startbtn_Callback calls timer start method if the timer is not already running: if strcmp(get(handles.timer, 'Running'), 'off') start(handles.timer); end stopbtn_Callback stopbtn_Callback calls the timer stop method if the timer is currently running: if strcmp(get(handles.timer, 'Running'), 'on') stop(handles.timer); end periodsldr_Callback periodsldr_Callback is called each time you move the slider.
Time Data Updates from a GUI (GUIDE) update_display update_display is the callback for the timer object. It adds Gaussian noise to the ZData of the surface plot: handles = guidata(hfigure); Z = get(handles.surf,'ZData'); Z = Z + 0.1*randn(size(Z)); set(handles.surf,'ZData',Z); Because update_display is not a GUIDE-generated callback, it does not include handles as one of its calling arguments. Instead, it accesses the handles structure by calling guidata.
10 Examples of GUIDE GUIs Other Uses for Timers in GUIs In addition to acquiring or processing data at regular intervals, you can use timers to implement other time-based procedures in a GUI: • Time-limit extended computations • Time-out pending connections • Start and stop simulations • Poll sets of devices • Administer tests For more information about programming timers in GUIs, see “Control Program Execution Using Timer Objects” on page 14-11.
Create GUIs Programmatically Chapter 11, Lay Out a Programmatic GUI (p. 11-1) Shows you how to create and organize the GUI code file and from there how to populate the GUI and construct menus and toolbars. Provides guidance in designing a GUI for cross-platform compatibility. Chapter 12, Code a Programmatic GUI (p. 12-1) Explains how user-written callback routines control GUI behavior. Shows you how to associate callbacks with specific components and explains callback syntax and arguments.
11 Lay Out a Programmatic GUI • “Design a Programmatic GUI” on page 11-2 • “Create and Run a Programmatic GUI” on page 11-4 • “Create Figures for Programmatic GUIs” on page 11-6 • “Add Components to a Programmatic GUI” on page 11-9 • “Compose and Code GUIs with Interactive Tools” on page 11-42 • “Set Tab Order in a Programmatic GUI” on page 11-70 • “Create Menus for a Programmatic GUI” on page 11-75 • “Create Toolbars for Programmatic GUIs” on page 11-88 • “Design Programmatic GUIs for Cross-Platform Compat
11 Lay Out a Programmatic GUI Design a Programmatic GUI Before creating the actual GUI, it is important to decide what it is you want your GUI to do and how you want it to work. It is helpful to draw your GUI on paper and envision what the user sees and what actions the user takes. Note MATLAB software provides a selection of standard dialog boxes that you can create with a single function call.
Design a Programmatic GUI Many Web sites and commercial publications such as the following provide guidelines for designing GUIs: • AskTog — Essays on good design and a list of First Principles for good user interface design. The author, Bruce Tognazzini, is a well-respected user interface designer. http://www.asktog.com/basics/firstPrinciples.html. • Galitz, Wilbert, O., Essential Guide to User Interface Design. Wiley, New York, NY, 2002.
11 Lay Out a Programmatic GUI Create and Run a Programmatic GUI In this section... “File Organization” on page 11-4 “File Template” on page 11-4 “Run the GUI” on page 11-5 File Organization Typically, a GUI code file has the following ordered sections. You can help to maintain the structure by adding comments that name the sections when you first create them. 1 Comments displayed in response to the MATLAB help command.
Create and Run a Programmatic GUI % to the help command. % (Leave a blank line following the help.) % Initialization tasks % Construct the components % Initialization tasks % Callbacks for MYGUI % Utility functions for MYGUI end The end statement that matches the function statement is necessary because this document treats GUI creation using nested functions. Save the file in your current folder or at a location that is on your MATLAB path.
11 Lay Out a Programmatic GUI Create Figures for Programmatic GUIs In MATLAB software, a GUI is a figure. Before you add components to it, create the figure explicitly and obtain a handle for it. In the initialization section of your file, use a statement such as the following to create the figure: fh = figure; where fh is the figure handle. Note If you create a component when there is no figure, MATLAB software creates a figure automatically but you do not know the figure handle.
Create Figures for Programmatic GUIs Property Values Description Resize on, off. Default is on. Determines if the user can resize the figure window with the mouse. Toolbar auto, none, figure. Default is auto. Display or hide the default figure toolbar. • none — do not display the figure toolbar. • auto — display the figure toolbar, but remove it if a user interface control (uicontrol) is added to the figure. • figure — display the figure toolbar.
11 Lay Out a Programmatic GUI The Position property is a four-element vector that specifies the location of the GUI on the screen and its size: [distance from left, distance from bottom, width, height]. Default units are pixels. If the figure were visible, it would look like this: The next topic, “Add Components to a Programmatic GUI” on page 11-9, shows you how to add push buttons, axes, and other components to the GUI.
Add Components to a Programmatic GUI Add Components to a Programmatic GUI In this section...
11 11-10 Lay Out a Programmatic GUI Component Function Description ActiveX actxcontrol ActiveX components enable you to display ActiveX controls in your GUI. They are available only on the Microsoft Windows platform. “Axes” on page 11-39 axes Axes enable your GUI to display graphics such as graphs and images. “Button Group” on page 11-36 uibuttongroup Button groups are like panels, but are used to manage exclusive selection behavior for radio buttons and toggle buttons.
Add Components to a Programmatic GUI Component Function Description “Panel” on page 11-35 uipanel Panels arrange GUI components into groups. By visually grouping related controls, panels can make the user interface easier to understand. A panel can have a title and various borders. Panel children can be user interface controls and axes, as well as button groups and other panels. The position of each component within a panel is interpreted relative to the panel.
11 11-12 Lay Out a Programmatic GUI Component Function Description “Slider” on page 11-28 uicontrol Sliders accept numeric input within a specified range by enabling the user to move a sliding bar, which is called a slider or thumb. Users move the slider by clicking the slider and dragging it, by clicking in the trough, or by clicking an arrow. The location of the slider indicates the relative location within the specified range.
Add Components to a Programmatic GUI Component Function Description group to manage mutually exclusive radio buttons. Toolbar Buttons uitoolbar, uitoggletool, uipushtool Non-modal GUIs can display toolbars, which can contain push buttons and toggle buttons, identified by custom icons and tooltips. Components are sometimes referred to by the name of the function used to create them. For example, a push button is created using the uicontrol function, and it is sometimes referred to as a uicontrol.
11 Lay Out a Programmatic GUI • “Check Box” on page 11-15 • “Edit Text” on page 11-17 • “List Box” on page 11-20 • “Pop-Up Menu” on page 11-22 • “Table” on page 11-24 • “Push Button” on page 11-25 • “Radio Button” on page 11-27 • “Slider” on page 11-28 • “Static Text” on page 11-30 • “Toggle Button” on page 11-31 Commonly Used Properties The most commonly used properties needed to describe a user interface control are shown in the following table: 11-14 Property Values Description Max Scalar.
Add Components to a Programmatic GUI Property Values Description String String. Can be a cell array or character array or strings. Component label. For list boxes and pop-up menus it is a list of the items. To display the & character in a label, use two & characters in the string. The words remove, default, and factory (case sensitive) are reserved. To use one of these as a label, prepend a backslash (\) to the string. For example, \remove yields remove.
11 Lay Out a Programmatic GUI cbh = uicontrol(fh,'Style','checkbox',... 'String','Display file extension',... 'Value',1,'Position',[30 20 130 20]); The first argument, fh, specifies the handle of the parent figure. You can also specify the parent as a panel or button group. See “Panel” on page 11-35 and “Button Group” on page 11-36 for more information. The Style property, checkbox, specifies the user interface control as a check box. The String property labels the check box as Display file extension.
Add Components to a Programmatic GUI Note You can also use an image as a label. See “Add an Image to a Push Button” on page 11-26 for more information. Edit Text The following statement creates an edit text component with handle eth: eth = uicontrol(fh,'Style','edit',... 'String','Enter your name here.',... 'Position',[30 50 130 20]); The first argument, fh, specifies the handle of the parent figure. You can also specify the parent as a panel or button group.
11 Lay Out a Programmatic GUI If Max-Min is less than or equal to 1, the edit text component admits only a single line of input. If you specify a component width that is too small to accommodate the specified string, MATLAB software displays only part of the string. The user can use the arrow keys to move the cursor over the entire string. The Position property specifies the location and size of the edit text component. In this example, the edit text is 130 pixels wide and 20 high.
Add Components to a Programmatic GUI font = FontName: FontWeight: FontAngle: FontSize: FontUnits: 'Century Schoolbook' 'normal' 'normal' 9 'points' . Note Not all fonts listed may be available to users of your GUI on their systems. You can then insert as much of the struct’s data as you need into a statement in your code file.
11 Lay Out a Programmatic GUI Instead of designating a font yourself, you could provide a push button or context menu in your GUI that allows users to select fonts themselves via the uisetfont GUI. The callback for the feature could be font = uisetfont; set(eth,'font') where eth is the handle for the edit box whose font the user is setting. You can store the handle in the figure’s AppData and retrieve it with getappdata.
Add Components to a Programmatic GUI String Property Format Example Cell array of strings {'one' 'two' 'three'} Padded string matrix ['one ';'two ';'three'] String vector separated by vertical slash (|) characters ['one|two|three'] If you specify a component width that is too small to accommodate one or more of the specified strings, MATLAB software truncates those strings with an ellipsis. The Value property specifies the item or items that are selected when the component is created.
11 Lay Out a Programmatic GUI If the list box is not large enough to display all list entries, you can set the ListBoxTop property to the index of the item you want to appear at the top when the component is created. The Position property specifies the location and size of the list box. In this example, the list box is 130 pixels wide and 80 high. It is positioned 30 pixels from the left of the figure and 20 pixels from the bottom.
Add Components to a Programmatic GUI The String property defines the menu items. You can specify the items in any of the formats shown in the following table.
11 Lay Out a Programmatic GUI Table The following code creates a table with handle th.
Add Components to a Programmatic GUI • Foreground and background colors. • Row striping. • Row labels/numbers. • Column labels/numbers. • Column formats and widths. • Font characteristics. Also, uitables have six callback functions that you can program. You can set most uitable properties using the Table Property Editor that you open from the Property Inspector instead of using the set command. This GUI lets you set properties for table rows, columns, colors, and data.
11 Lay Out a Programmatic GUI The Style property, pushbutton, specifies the user interface control as a push button. Because pushbutton is the default style, you can omit the 'Style' property from the statement. The String property labels the push button as Button 1. The push button allows only a single line of text. If you specify more than one line, only the first line is shown.
Add Components to a Programmatic GUI Note Create your own icon with the icon editor described in “Icon Editor” on page 15-63. See ind2rgb for information on converting a matrix X and corresponding colormap, i.e., an (X, MAP) image, to RGB (truecolor) format. Radio Button The following statement creates a radio button with handle rbh: rbh = uicontrol(fh,'Style','radiobutton',... 'String','Indent nested functions.',...
11 Lay Out a Programmatic GUI The Value property specifies whether the radio button is selected when the component is created. Set Value to the value of the Max property (default is 1) to create the component with the radio button selected. Set Value to Min (default is 0) to leave the radio button unselected. The Position property specifies the location and size of the radio button. In this example, the radio button is 150 pixels wide and 20 high.
Add Components to a Programmatic GUI • Specify the value indicated by the slider when it is created by setting the Value property to the appropriate number. This number must be less than or equal to Max and greater than or equal to Min. If you specify Value outside the specified range, the slider is not displayed. • The slider Value changes by a small amount when a user clicks the arrow button, and changes by a larger amount when the user clicks the trough (also called the channel).
11 Lay Out a Programmatic GUI Note On Mac platforms, the height of a horizontal slider is constrained. If the height you set in the position vector exceeds this constraint, the displayed height of the slider is the maximum allowed. The height element of the position vector is not changed. The slider component provides no text description or data entry capability. Use a “Static Text” on page 6-48 component to label the slider.
Add Components to a Programmatic GUI The Position property specifies the location and size of the static text component. In this example, the static text is 130 pixels wide and 20 high. It is positioned 30 pixels from the left of the figure and 50 pixels from the bottom. The statement assumes the default value of the Units property, which is pixels. Toggle Button The following statement creates a toggle button with handle tbh: tbh = uicontrol(fh,'Style','togglebutton',... 'String','Left/Right Tile',...
11 Lay Out a Programmatic GUI accommodate the specified String, MATLAB software truncates the string with an ellipsis. The Value property specifies whether the toggle button is selected when the component is created. Set Value to the value of the Max property (default is 1) to create the component with the toggle button selected (depressed). Set Value to Min (default is 0) to leave the toggle button unselected (raised). The following figure shows the toggle button in the depressed position.
Add Components to a Programmatic GUI A syntax for panels is ph = uipanel(fh,'PropertyName',PropertyValue,...) where ph is the handle of the resulting panel. The first argument, fh, specifies the handle of the parent figure. You can also specify the parent as a panel or button group. See the uipanel reference page for other valid syntaxes. A syntax for button groups is bgh = uibuttongroup('PropertyName',PropertyValue,...) where bgh is the handle of the resulting button group.
11 Lay Out a Programmatic GUI Property Values Description Parent Handle Handle of the component’s parent figure, panel, or button group. Position 4-element vector: [distance from left, distance from bottom, width, height]. Default is [0, 0, 1, 1]. Size of the component and its location relative to its parent. Title String Component label. To display the & character in a label, use two & characters in the string. The words remove, default, and factory (case sensitive) are reserved.
Add Components to a Programmatic GUI Panel The following statement creates a panel with handle ph. Use a panel to group components in the GUI. ph = uipanel('Parent',fh,'Title','My Panel',... 'Position',[.25 .1 .5 .8]); The Parent property specifies the handle fh of the parent figure. You can also specify the parent as a panel or button group. The Title property labels the panel as My Panel. The statement assumes the default TitlePosition property, which is lefttop.
11 Lay Out a Programmatic GUI figure and 10 percent of the figure height from the bottom. As the figure is resized the panel retains these proportions. The following statements add two push buttons to the panel with handle ph. The Position property of each component within a panel is interpreted relative to the panel. pbh1 = uicontrol(ph,'Style','pushbutton','String','Button 1',... 'Units','normalized',... 'Position',[.1 .55 .8 .3]); pbh2 = uicontrol(ph,'Style','pushbutton','String','Button 2',...
Add Components to a Programmatic GUI The Parent property specifies the handle fh of the parent figure. You can also specify the parent as a panel or button group. The Title property labels the button group as My Button Group. The statement assumes the default TitlePosition property, which is lefttop. The Units property is used to interpret the Position property. This button group assumes the default Units property, normalized. This enables the button group to resize automatically if the figure is resized.
11 Lay Out a Programmatic GUI 'Position',[.1 .6 .3 .2]); rbh2 = uicontrol(bgh,'Style','radiobutton','String','Blue',... 'Units','normalized',... 'Position',[.1 .2 .3 .2]); By default, the software automatically selects the first radio button added to a button group. You can use the radio button Value property to explicitly specify the initial selection. See “Radio Button” on page 11-27 for information.
Add Components to a Programmatic GUI • “Axes” on page 11-39 Commonly Used Properties The most commonly used properties needed to describe an axes are shown in the following table: Property Values Description HandleVisibility on, callback, off. Default is on. Determines if an object’s handle is visible in its parent’s list of children. For axes, set HandleVisibility to callback to protect them from command line operations. NextPlot add, replace, replacechildren.
11 Lay Out a Programmatic GUI ah = axes('Parent',fh,'Position',[.15 .15 .7 .7]); The Parent property specifies the handle fh of the parent figure. You can also specify the parent as a panel or button group. The Units property interprets the Position property. This axes assumes the default Units property, normalized. This enables the axes to resize automatically if the figure is resized.
Add Components to a Programmatic GUI The software automatically adds the tick marks. Most functions that draw in the axes update the tick marks appropriately. Prevent Customized Axes Properties from Being Reset. Data graphing functions, such as plot, image, scatter, and many others by default reset axes properties before they draw into an axes. This can be a problem in a GUI where you might need to maintain consistency of axes limits, ticks, axis colors, and font characteristics from one plot to another.
11 Lay Out a Programmatic GUI Compose and Code GUIs with Interactive Tools In this section... “Set Positions of Components Interactively” on page 11-43 “Align Components” on page 11-53 “Set Colors Interactively” on page 11-60 “Set Font Characteristics Interactively” on page 11-62 “Generate Code to Set Component Properties” on page 11-64 Laying out a programmatic GUI can take time and involves many small steps.
Compose and Code GUIs with Interactive Tools Some of these tools return property values, while others let you edit properties interactively without returning their values. In particular, the Property Inspector lets you interactively set almost any object property. You then can copy property values and paste them into the Command Window or a code file. However, when you capture vector-valued properties, such as Color or Position, the Inspector only lets you copy values one number at a time.
11 Lay Out a Programmatic GUI 4 Make sure that you know the handle of the component you have manipulated. In the following code, the handle is a variable named object_handle. 5 Obtain the component position vector from the Property Inspector. Type inspect or enter a get statement, such as: get(object_handle, 'Position') ans = 15.2500 333.0000 106.0000 20.0000 6 Copy the result (ans) and insert it in a set statement in your code file, within square brackets: set(object_handle, 'Position', [15.
Compose and Code GUIs with Interactive Tools rect = get(handle,'Position'); inspect(handle) To experiment with the function, enter the following code in the Command Window: hfig = figure; hsl = uicontrol('Style','slider') editpos(hsl) After you call editpos, the following prompt appears: === Select, move and resize the object. Use mouse and arrow keys. === When you are finished, press Return to continue. When you first enter plot edit mode, the selection is figure itself.
11 Lay Out a Programmatic GUI Use Plot Edit Mode to Change Properties After you select an object in plot edit mode, you can open the Property Inspector to view and modify any of its properties. While the object is selected, in the Command Window type: inspect You also can use the functional form to pass in the handle of the object you want to inspect, for example: inspect(hsl) The Property Inspector opens, displaying the object properties.
Compose and Code GUIs with Interactive Tools Scroll in the help window to view descriptions of other properties. Click the X close box to close the window. The following Inspector image illustrates using the Inspector to change the Max property of a slider uicontrol from its default value (1.0) to 10.0. Edit with the Property Editor The Property Editor has a more graphical interface than the Property Inspector. The interface is convenient for setting properties that affect the appearance of components.
11 Lay Out a Programmatic GUI shows the BackgroundColor and String properties of a list box altered using the Property Editor. Most of the properties that the Property Editor can set are cosmetic. To modify values for other properties, click More Properties. The Property Inspector opens (or, if already open, receives focus) to display properties of the selected object. Use it to change properties that the Property Editor does not display.
Compose and Code GUIs with Interactive Tools You can obtain the new property value by running the get function: value = get(object_handle, 'PropertyName') Transfer the value to your GUI program file. Either include it as a parameter-value pair in the statement creating the object, or as a set command for it later in the file. For some tools and techniques that aid in programming properties, see “Generate Code to Set Component Properties” on page 11-64.
11 Lay Out a Programmatic GUI set(object_handle,'Position',rect) set(object_handle,'Units',myunits) else rect = []; end clipboard('copy', rect) % Place set string on system % clipboard as well as returning it The setpos function uses figure units to set the component Position property. First, setpos gets and saves the Units property of the component, and sets that property to figure units. After setting the object position, the function restores the original units of the object.
Compose and Code GUIs with Interactive Tools 3 Release the mouse button. The control moves. 4 The button Position is set, returned and placed on the system clipboard: rect = 37 362 127 27 Add a Position parameter and empty value to the uicontrol command from step 1 in your GUI code file, as follows: btn1 = uicontrol('Style','pushbutton',...
11 Lay Out a Programmatic GUI btn1 = uicontrol('Style','pushbutton',... 'String','Push Me','Position',[37 362 127 27]) You cannot call setpos when you are creating a component because setpos requires the handle of the component as an argument. However, you can create a small function that lets you position a component interactively as you create it.
Compose and Code GUIs with Interactive Tools 5 Place your cursor between the empty brackets and type Ctrl+V, or right-click and select Paste. Allowing for differences in coordinate values, the statement looks like this one: btn1 = uicontrol('Style','pushbutton','String','Push Me',... 'Position',[55 253 65 25]); Remember that rbbox returns coordinates in figure units ('pixels', in this example).
11 Lay Out a Programmatic GUI also distribute the components evenly across their span or specify a fixed distance between them. A syntax for the align function is align(HandleList,'HorizontalAlignment','VerticalAlignment') The following table lists the possible values for these parameters. HorizontalAlignment VerticalAlignment None, Left, Center, Right, Distribute, or Fixed None, Top, Middle, Bottom, Distribute, or Fixed All handles in HandleList must have the same parent.
Compose and Code GUIs with Interactive Tools Note Each of the three following align examples starts with these unaligned push buttons and repositions them in different ways. In practice, when you create buttons with uicontrol and do not specify a Position, their location is always [20 20 60 20] (in pixels). That is, if you keep creating them with default positions, they lie on top of one another. Align Components Horizontally.
11 Lay Out a Programmatic GUI Align Components Vertically While Distributing Them Horizontally. The following statement moves the push buttons to the bottom of their bounding box. It also adjusts their horizontal placement to create a fixed distance of five points between the boxes. The push buttons appear at the bottom of the original bounding box.
Compose and Code GUIs with Interactive Tools Use Align Distribute Tools If your figure has a standard menu bar, you can perform align and distribute operations on selected components directly in plot edit mode. Several options from the Tools menu save you from typing align function commands. The align and distribute menu items are highlighted in the following illustration.
11 Lay Out a Programmatic GUI The following steps illustrate how to use the Align Distribute tool to arrange components in a GUI. The tool provides the same options as the align function. discussed in “Use the align Function” on page 11-53. 1 Select Tools > Edit Plot. 2 Select the components that you want to align. 3 Select Tools > Align Distribute Tool. 4 In the Vertical panel chose the third Distribute option (the same as the align function Middle VerticalAlignment option).
Compose and Code GUIs with Interactive Tools The buttons align as shown. Note One thing to remember when aligning components is that the align function uses units of points while the Align Distribute GUI uses units of pixels. Neither method changes the Units property of the components you align, however. You can also select the Align or Distribute option from the figure Tools menu to perform either operation immediately. For example, here are the six options available from the Align menu item.
11 Lay Out a Programmatic GUI For more information, see “Align/Distribute Menu Options”.
Compose and Code GUIs with Interactive Tools of colors. The uisetcolor function opens a GUI that returns color values you can plug into components when you create them or later, by using set. For example, the statement: set(object_handle,'BackgroundColor',uisetcolor) opens a color selector GUI for you to choose a color. When you click OK, it returns an RGB color vector that set assigns immediately.
11 Lay Out a Programmatic GUI Set Font Characteristics Interactively The uisetfont GUI gives you access to the characteristics of all fonts on your system. Use it to set font characteristics for any component that displays text. It returns a structure containing data that describes the property values you chose. FontData = uisetfont(object_handle) FontData = FontName: FontWeight: FontAngle: FontSize: FontUnits: 'Arial' 'bold' 'normal' 10 'points' uisetfont returns all font characteristics at once.
Compose and Code GUIs with Interactive Tools 'String',inputdlg('String','Static Text'),... uisetfont,'Position',getrect) The inputdlg dialog box appears first, as shown here. After you enter a string and click OK, the uisetfont dialog box opens for you to set font characteristics for displaying the string. When you specify a font, style, and size and click OK, the getrect function executes (see “Sketch a Position Vector” on page 11-49).
11 Lay Out a Programmatic GUI Generate Code to Set Component Properties The techniques described in the preceding sections set properties of components interactively. However, you still need to create code in your GUI code file to enter the property values.
Compose and Code GUIs with Interactive Tools Help system that contains doc examples. See “View and Run the setprop Function” on page 11-68. Property values need not be character strings.
11 Lay Out a Programmatic GUI for the current value of the property, or '' for an invalid property name. setstr = setprop(objhandle,property,value) returns a SET command for the specified value of the property, or '' for an invalid property name or value. If property is empty, the listbox GUI opens to let you choose a property name. The value can be a string, scalar, vector, cell array, HG handle or function handle. Properties consisting of structs or objects are disregarded and return '' (empty).
Compose and Code GUIs with Interactive Tools setprop(object_handle,'pos') ans = set(object_handle,'Position',[20 20 60 20]) If you omit the property name, the function displays a GUI listing all the properties of the object. setprop(object_handle) When you select a property name from the list and click OK, setprop returns a set string for that property and its current value: ans = set(btn1,'FontName','MS Sans Serif') The setprop function places its return value on the system clipboard.
11 Lay Out a Programmatic GUI Tip You can provide an empty property name followed by a value when you call setprop. Then, the function attempts to assign that value to the property you choose in the GUI. Call setprop this way when you know the value you want to assign, but are unsure of how to spell the property name. Some property values (for example, matrices or cell arrays) can generate long statements. You can break long commands into continuation lines (...
Compose and Code GUIs with Interactive Tools 1 Click here to add all GUI example files to the MATLAB path (only for the current session). 2 Type edit setprop or click here to open the file in the MATLAB Editor (read only) Caution Do not save examples you have modified to the examples folder from where you obtained them, or you will overwrite the original files. Save them to your current folder or another folder that you work in.
11 Lay Out a Programmatic GUI Set Tab Order in a Programmatic GUI In this section... “How Tabbing Works” on page 11-70 “Default Tab Order” on page 11-70 “Change the Tab Order” on page 11-73 How Tabbing Works A GUI’s tab order is the order in which components of the GUI acquire focus when a user presses the keyboard Tab key. Focus is generally denoted by a border or a dotted border. Tab order is determined separately for the children of each parent.
Set Tab Order in a Programmatic GUI 'String',{'peaks','membrane','sinc'},... 'Position',[290 200 130 20]); sth = uicontrol(fh,'Style','text','String','Select Data',... 'Position',[290 230 60 20]); ph = uipanel('Parent',fh,'Units','pixels',... 'Position',[290 30 130 150]); ah = axes('Parent',fh,'Units','pixels',... 'Position',[40 30 220 220]); bh1 = uicontrol(ph,'Style','pushbutton',... 'String','Contour','Position',[20 20 80 30]); bh2 = uicontrol(ph,'Style','pushbutton',...
11 Lay Out a Programmatic GUI where ph is the handle of the panel. This statement returns a vector containing the handles of the children, the three push buttons. ch = 4.0076 3.0076 2.0076 These handles correspond to the push buttons as shown in the following table: Handle Handle Variable Push Button 4.0076 bh3 Surf 3.0076 bh2 Mesh 2.0076 bh1 Contour The default tab order of the push buttons is the reverse of the order of the child vector: Contour > Mesh > Surf.
Set Tab Order in a Programmatic GUI Change the Tab Order Use the uistack function to change the tab order of components that have the same parent. A convenient syntax for uistack is uistack(h,stackopt,step) where h is a vector of handles of the components whose tab order is to be changed. stackopt represents the direction of the move. It must be one of the strings: up, down, top, or bottom, and is interpreted relative to the column vector returned by the statement: ch = get(ph,'Children') ch = 4.0076 3.
11 Lay Out a Programmatic GUI Note Tab order also affects the stacking order of components. If components overlap, those that appear lower in the child order, are drawn on top of those that appear higher in the order. If the push buttons in the example overlapped, the Contour push button would be on top.
Create Menus for a Programmatic GUI Create Menus for a Programmatic GUI In this section... “Add Menu Bar Menus” on page 11-75 “Add Context Menus to a Programmatic GUI” on page 11-81 Add Menu Bar Menus Use the uimenu function to add a menu bar menu to your GUI. A syntax for uimenu is mh = uimenu(parent,'PropertyName',PropertyValue,...) Where mh is the handle of the resulting menu or menu item. See the uimenu reference page for other valid syntaxes.
11 Lay Out a Programmatic GUI If you use the standard menu bar menus, any menus you create are added to it. If you choose not to display the standard menu bar menus, the menu bar contains only the menus that you create. If you display no standard menus and you create no menus, the menu bar itself does not display. Note On Mac platforms, MATLAB creates menus on the menu bar at the top of the screen, to the right of the right-most existing menu, not at the top of figure windows.
Create Menus for a Programmatic GUI Property Values HandleVisibility on, off. Default is on. Label String Description Determines if an object’s handle is visible in its parent’s list of children. For menus, set HandleVisibility to off to protect menus from operations not intended for them. Menu label. To display the & character in a label, use two & characters in the string. The words remove, default, and factory (case sensitive) are reserved.
11 Lay Out a Programmatic GUI Figure windows with a standard menu bar also have a Desktop menu from which the user can dock and undock them. To display the docking arrow and the Desktop > Dock Figure menu item, the figure property DockControls must be set to 'on'. You can set it in the Property Inspector. In addition, the MenuBar and/or ToolBar figure properties must be set to 'on' to display docking controls. The WindowStyle figure property also affects docking behavior.
Create Menus for a Programmatic GUI Menu Bar Menu The following statements create a menu bar menu with two menu items. mh = uimenu(fh,'Label','My menu'); eh1 = uimenu(mh,'Label','Item 1'); eh2 = uimenu(mh,'Label','Item 2','Checked','on'); fh is the handle of the parent figure. mh is the handle of the parent menu. The Label property specifies the text that appears in the menu. The Checked property specifies that this item is displayed with a check next to it when the menu is created.
11 Lay Out a Programmatic GUI The following statement adds a separator line preceding the second menu item. set(eh2,'Separator','on'); The following statements add two menu subitems to Item 1, assign each subitem a keyboard accelerator, and disable the first subitem. seh1 = uimenu(eh1,'Label','Choice 1','Accelerator','C',... 'Enable','off'); seh2 = uimenu(eh1,'Label','Choice 2','Accelerator','H'); The Accelerator property adds keyboard accelerators to the menu items.
Create Menus for a Programmatic GUI Note After you have created all menu items, set their HandleVisibility properties off by executing the following statements: menuhandles = findall(figurehandle,'type','uimenu'); set(menuhandles,'HandleVisibility','off') See “Program Menu Items” on page 12-34 for information about programming menu items. Add Context Menus to a Programmatic GUI Context menus appear when the user right-clicks on a figure or GUI component.
11 Lay Out a Programmatic GUI Property Values Description HandleVisibility on, off. Default is on. Determines if an object’s handle is visible in its parent’s list of children. For menus, set HandleVisibility to off to protect menus from operations not intended for them. Parent Figure handle Handle of the context menu’s parent figure. Position 2-element vector: [distance from left, distance from bottom]. Default is [0 0].
Create Menus for a Programmatic GUI fh = figure('Position',[300 300 400 225]); cmenu = uicontextmenu('Parent',fh,'Position',[10 215]); At this point, the figure is visible, but not the menu. Note “Force Display of the Context Menu” on page 11-86 explains the use of the Position property. Add Menu Items to the Context Menu Use the uimenu function to add items to the context menu. The items appear on the menu in the order in which you add them.
11 Lay Out a Programmatic GUI You can use any applicable Uimenu Properties such as Checked or Separator when you define context menu items. See the uimenu reference page and “Add Menu Bar Menus” on page 11-75 for information about using uimenu to create menu items. Note that context menus do not have an Accelerator property.
Create Menus for a Programmatic GUI This code associates the context menu with the figure and with the axes by setting the UIContextMenu property of the figure and the axes to the handle cmenu of the context menu.
11 Lay Out a Programmatic GUI Right-click on the figure or on the axes. The context menu appears with its upper-left corner at the location you clicked. Right-click on the panel or its push button. The context menu does not appear. Force Display of the Context Menu If you set the context menu Visible property on, the context menu is displayed at the location specified by the Position property, without the user taking any action. In this example, the context menu Position property is [10 215].
Create Menus for a Programmatic GUI The context menu is displayed 10 pixels from the left of the figure and 215 pixels from the bottom. If you set the context menu Visible property to off, or if the user clicks the GUI outside the context menu, the context menu disappears.
11 Lay Out a Programmatic GUI Create Toolbars for Programmatic GUIs In this section... “Use the uitoolbar Function” on page 11-88 “Commonly Used Properties” on page 11-88 “Toolbars” on page 11-89 “Display and Modify the Standard Toolbar” on page 11-92 Use the uitoolbar Function Use the uitoolbar function to add a custom toolbar to your GUI. Use the uipushtool and uitoggletool functions to add push tools and toggle tools to a toolbar. A push tool functions as a push button.
Create Toolbars for Programmatic GUIs Property Values Description CData 3-D array of values between 0.0 and 1.0 n-by-m-by-3 array of RGB values that defines a truecolor image displayed on either a push button or toggle button. HandleVisibility on, off. Default is on. Determines if an object’s handle is visible in its parent’s list of children. For toolbars and their tools, set HandleVisibility to off to protect them from operations not intended for them. Separator off, on. Default is off.
11 Lay Out a Programmatic GUI img1(:,:,1) = repmat(a,16,1)' img1(:,:,2) = repmat(a,16,1); img1(:,:,3) = repmat(flipdim(a,2),16,1); pth = uipushtool(th,'CData',img1,... 'TooltipString','My push tool',... 'HandleVisibility','off') % Add a toggle tool to the toolbar img2 = rand(16,16,3); tth = uitoggletool(th,'CData',img2,'Separator','on',... 'TooltipString','Your toggle tool',... 'HandleVisibility','off') fh is the handle of the parent figure. th is the handle of the parent toolbar.
Create Toolbars for Programmatic GUIs TooltipString specifies the tooltips for the push tool and the toggle tool as My push tool and Your toggle tool, respectively. In this example, setting the toggle tool Separator property to on creates a dividing line to the left of the toggle tool. You can change the order of the tools by modifying the child vector of the parent toolbar. For this example, execute the following code to reverse the order of the tools.
11 Lay Out a Programmatic GUI Note After you have created a toolbar and its tools, set their HandleVisibility properties off by executing statements similar to the following: set(toolbarhandle,'HandleVisibility','off') toolhandles = get(toolbarhandle,'Children'); set(toolhandles,'HandleVisibility','off') Display and Modify the Standard Toolbar You can choose whether or not to display the MATLAB standard toolbar on your GUI. You can also add or delete tools from the standard toolbar.
Create Toolbars for Programmatic GUIs Modify the Standard Toolbar Once you have the handle of the standard toolbar, you can add tools, delete tools, and change the order of the tools. Add a tool the same way you would add it to a custom toolbar. The following code retrieves the handle of the MATLAB standard toolbar and adds to the toolbar a toggle tool similar to the one defined in “Toolbars” on page 11-89. fh is the handle of the figure.
11 Lay Out a Programmatic GUI Design Programmatic GUIs for Cross-Platform Compatibility In this section... “Default System Font” on page 11-94 “Standard Background Color” on page 11-95 “Cross-Platform Compatible Units” on page 11-96 Default System Font By default, user interface controls (uicontrols) use the default font for the platform on which they are running. For example, when displaying your GUI on PCs, user interface controls use MS San Serif.
Design Programmatic GUIs for Cross-Platform Compatibility Use a Specific Font Name You can specify an actual font name (such as Times or Courier) for the FontName property. However, doing so may cause your GUI to appear differently than you intended when run on a different computer. If the target computer does not have the specified font, it substitutes another font that may not look good in your GUI or may not be the standard font used for GUIs on that system.
11 Lay Out a Programmatic GUI The following figures illustrate the results with and without system color matching. Cross-Platform Compatible Units Cross-platform compatible GUIs should look correct on computers having different screen sizes and resolutions. Since the size of a pixel can vary on different computer displays, using the default figure Units of pixels does not produce a GUI that looks the same on all platforms.
Design Programmatic GUIs for Cross-Platform Compatibility ResizeFcn enables you to customize the GUI’s resize behavior and is valid only if you set Resize to on. ResizeFcn is the handle of a user-written callback that is executed when a user resizes the GUI. It controls the resizing of all components in the GUI. See documentation for the figure ResizeFcn property for an example of resizing. The following table shows appropriate Units settings based on the resize behavior of your GUI.
11 Lay Out a Programmatic GUI Normalized. Normalized units represent a percentage of the size of the parent. The value of normalized units lies between 0 and 1. For example, if a panel contains a push button and the button units setting is normalized, then the push button Position setting [.2 .2 .6 .
12 Code a Programmatic GUI • “Organize a Programmatic GUI File” on page 12-2 • “Initialize a Programmatic GUI” on page 12-3 • “Write Code for Callbacks” on page 12-7 • “Examples: Program GUI Components” on page 12-20
12 Code a Programmatic GUI Organize a Programmatic GUI File After laying out your GUI, program its behavior. This chapter addresses the programming of GUIs created programmatically. Specifically, it discusses data creation, GUI initialization, and the use of callbacks to control GUI behavior. The following ordered list shows these topics within the organization of the typical GUI code file. 1 Comments displayed in response to the MATLAB help command.
Initialize a Programmatic GUI Initialize a Programmatic GUI When you open a GUI, it usually initializes certain data structures and variable values. These actions can include: • Defining variables for supporting input and output arguments. See “Declare Variables for Input and Output Arguments” on page 12-4. • Defining default values for input and output arguments. • Defining custom property values used for constructing the components. See “Define Custom Property/Value Pairs” on page 12-4.
12 Code a Programmatic GUI Examples If you are reading this in the MATLAB Help Browser, use the following links to view the complete code files for these initialization examples in the Editor: • Color Palette • Icon Editor Declare Variables for Input and Output Arguments These are typical declarations for input and output arguments. They are taken from example “Icon Editor” on page 15-63.
Initialize a Programmatic GUI The fullfile function builds a full filename from parts. The following statements each start the Icon Editor. The first one could be used to create a new icon. The second one could be used to edit an existing icon file. cdata = iconEditor('iconwidth',16,'iconheight',25) cdata = iconEditor('iconfile','eraser.
12 Code a Programmatic GUI Most components have Visible properties. You can also use these properties to make individual components invisible. Return Output to the User If your GUI function provides for an argument to the left of the equal sign, and the user specifies such an argument, then you want to return the expected output. The code that provides this output usually appears just before the GUI main function returns.
Write Code for Callbacks Write Code for Callbacks In this section... “What Is a Callback?” on page 12-7 “Kinds of Callbacks” on page 12-8 “Specify Callbacks in Function Calls” on page 12-11 What Is a Callback? A callback is a function that you write and associate with a specific component in the GUI or with the GUI figure itself. The callbacks control GUI or component behavior by performing some action in response to an event for its component.
12 Code a Programmatic GUI Kinds of Callbacks The GUI figure and each type of component has specific kinds of callbacks with which you can associate it. The callbacks that are available for each component are defined as properties of that component. For example, a push button has five callback properties: ButtonDownFcn, Callback, CreateFcn, DeleteFcn, and KeyPressFcn. A panel has four callback properties: ButtonDownFcn, CreateFcn, DeleteFcn, and ResizeFcn.
Write Code for Callbacks Callback Property Triggering Event Components ClickedCallback Control action. Executes when the push tool or toggle tool is clicked. For the toggle tool, this is independent of its state. Push tool, toggle tool CloseRequestFcn Executes when the figure closes. Figure CreateFcn Initializes the component when it is created. It executes after the component or figure is created, but before it is displayed.
12 12-10 Code a Programmatic GUI Callback Property Triggering Event Components ResizeFcn Executes when a user resizes a panel, button group, or figure whose figure Resize property is set to On. Figure, button group, panel SelectionChangeFcn Executes when a user selects a different radio button or toggle button in a button group component. Button group WindowButtonDownFcn Executes when you press a mouse button while the pointer is in the figure window.
Write Code for Callbacks Note User interface controls include push buttons, sliders, radio buttons, check boxes, editable text boxes, static text boxes, list boxes, and toggle buttons. They are sometimes referred to as uicontrols. Follow the links in the preceding table to see ways in which specific callbacks are used. To get specific information for a given callback property, check the properties reference page for your component, e.g.
12 Code a Programmatic GUI You can attach a callback when you create a component by supplying the callback’s property name and value (its calling sequence). You can also add or replace a callback at a later time using the set command. The examples that follow all use set, a recommended practice because some of the parameters a callback specifies might not exist or have the required values at the time a component is created.
Write Code for Callbacks You can concatenate commands in a string callback. This one, for example, adds a title to the plot it creates. set(hb,'Callback',... 'plot(myvar,''--m''); title(''String Callback'')') Note Double single quotation marks are needed around any strings that exist within the string.
12 Code a Programmatic GUI function display_slider_value(hObject,eventdata) disp(['Slider moved to ' num2str(get(hObject,'Value'))]); When you click an arrow on the slider, the output of the function looks like this: Slider moved to 0.01 Slider moved to 0.02 ... Both sections of code must exist in the same GUI code file. Include the one that defines the uicontrol in a function that sets up the GUI, normally the main function. Add the callback function as a subfunction or a nested function.
Write Code for Callbacks that you specify. Place single quotes around the function name and any literal string arguments, but not around workspace variable name arguments. The function must exist on the MATLAB path, and needs to have at least two arguments. The first two (which MATLAB automatically inserts) are • The handle of the component whose callback is now being called. • Event data (a MATLAB struct that several figure and GUI component callbacks provide, but most pass an empty matrix).
12 Code a Programmatic GUI function pushbutton_callback(hObject, eventdata, var1, var2) plot(var1,var2) When you run this GUI by pressing the push button, you see a line graph of myvar appearing as a magenta dashed line, similar to the following (graphs can differ due to using the rand function to generate data). Because the value of myvar was copied into the callback when it was set, clicking the button always produces the same plot, even if the value of myvar changes in the base workspace.
Write Code for Callbacks Use Cell Arrays with Function Handles. You can specify a callback function using a function handle instead of using a function name. The major benefit to using function handles is the capability to define functions on the fly—by executing code that sets a component’s callback to the handle of a function defined within its scope, for example, an anonymous function.
12 Code a Programmatic GUI Note Unless you declare them as strings (with required arguments, as described in “Use String Callbacks” on page 12-12), do not use regular functions as callbacks. If you do, the functions can generate errors or behave unpredictably. Because MATLAB GUI component callbacks include autogenerated arguments, you cannot simply specify a regular MATLAB or toolbox function name or function handle (for example, plot or @plot) as a callback.
Write Code for Callbacks GUI Component Callbacks with Event Data Property Reference Pages Figure KeyPressFcn, KeyReleaseFcn, WindowKeyPressFcn, WindowKeyReleaseFcn, WindowScrollWheel Figure Properties User interface control (uicontrol) KeyPressFcn Uicontrol Properties Button group (uibuttongroup) SelectionChangeFcn Uibuttongroup Properties Table (uitable) CellEditCallback, CellSelectionCallback Uitable Properties Share Callbacks Among Components If you are designing a GUI and programming it
12 Code a Programmatic GUI Examples: Program GUI Components In this section...
Examples: Program GUI Components Check Box You can determine the current state of a check box from within any of its callbacks by querying the state of its Value property, as illustrated in the following example: function checkbox1_Callback(hObject,eventdata) if (get(hObject,'Value') == get(hObject,'Max')) % Checkbox is checked-take appropriate action else % Checkbox is not checked-take appropriate action end hObject is the handle of the component for which the event was triggered.
12 Code a Programmatic GUI Retrieve Numeric Data from an Edit Text Component. MATLAB software returns the value of the edit text String property as a character string. If you want users to enter numeric values, you must convert the characters to numbers. You can do this using the str2double command, which converts strings to doubles. If the user enters nonnumeric characters, str2double returns NaN. You can use code similar to the following in an edit text callback.
Examples: Program GUI Components • Ctrl+V – Paste • Ctrl+H – Delete last character • Ctrl+A – Select all List Box When the list box Callback callback is triggered, the list box Value property contains the index of the selected item, where 1 corresponds to the first item in the list. The String property contains the list as a cell array of strings. This example retrieves the selected string. Note that it is necessary to convert the value of the String property from a cell array to a string.
12 Code a Programmatic GUI open on the second click. The callback can query the figure SelectionType property to determine if it was a single or double click. List Box Examples. See the following examples for more information on using list boxes: • “List Box Directory Reader (GUIDE)” on page 10-54 — 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 the filename.
Examples: Program GUI Components You can also select a menu item programmatically by setting the pop-up menu Value property to the index of the desired item. For example, set(pmh,'Value',2) selects the second item in the pop-up menu with handle pmh. Use the Index to Determine the Selected String. This example retrieves the actual string selected in the pop-up menu. It uses the pop-up menu Value property to index into the list of strings.
12 Code a Programmatic GUI close(gcbf) gcbf returns the handle of the figure containing the object whose callback is executing.
Examples: Program GUI Components slider_value = get(hObject,'Value'); % Proceed with callback... The Max and Min properties specify the slider’s maximum and minimum values. The slider’s range is Max - Min. hObject is the handle of the component for which the event was triggered. Toggle Button The callback for a toggle button needs to query the toggle button to determine what state it is in.
12 Code a Programmatic GUI Note You can use a button group to manage exclusive selection behavior for toggle buttons. See “Button Group” on page 12-28 for more information. Program Panels and Button Groups These topics provide basic code examples for panels and button group callbacks. The examples assume that callback properties are specified using function handles, enabling MATLAB software to pass arguments hObject, which is the handle of the component for which the event was triggered, and eventdata.
Examples: Program GUI Components set of radio buttons, toggle buttons, or both, the button group allows only one of them to be selected. When a user clicks a button, that button is selected and all other buttons are deselected. When programming a button group, you do not code callbacks for the individual buttons; instead, use its SelectionChangeFcn callback to manage responses to selections.
12 Code a Programmatic GUI The button group SelectionChangeFcn callback is called whenever a selection is made. If you have a button group that contains a set of radio buttons and toggle buttons and you want: • An immediate action to occur when a radio button or toggle button is selected, you must include the code to control the radio and toggle buttons in the button group’s SelectionChangeFcn callback function, not in the individual toggle button Callback functions.
Examples: Program GUI Components Program Axes Axes components enable your GUI to display graphics, such as graphs and images. This topic briefly tells you how to plot to an axes in your GUI. In most cases, you create a plot in an axes from a callback that belongs to some other component in the GUI. For example, pressing a button might trigger the plotting of a graph to an axes. In this case, the button’s Callback callback contains the code that generates the plot.
12 Code a Programmatic GUI 2 Run the GUI by typing two_axes at the command line. This is what the example looks like before you click the push buttons. 3 Click the Plot 1 button to display the contour plot in the first axes. Click the Plot 2 button to display the surf plot in the second axes.
Examples: Program GUI Components See “GUI with Multiple Axes (GUIDE)” on page 10-2 for a more complex example that uses two axes. If your GUI contains axes, you should ensure that their HandleVisibility properties are set to callback. This allows callbacks to change the contents of the axes and prevents command line operations from doing so. The default is on. When drawing anything into axes, a GUI’s code should specify the handle of the axes to use.
12 Code a Programmatic GUI • Properties that you can set to control many aspects of axes behavior and appearance, see “Axes Objects — Defining Coordinate Systems for Graphs”. • Creating axes in a tiled pattern, see the subplot function reference page. Program ActiveX Controls For information about programming ActiveX controls, see: • “Responding to Events — an Overview” • “Writing Event Handlers” See “MATLAB COM Client Support” for general information.
Examples: Program GUI Components When a user selects Edit > Copy > to file, no Copy callback is needed to perform the action. Only the Callback callback associated with the to file item is required. Suppose, however, that only certain objects can be copied to a file. You can use the Copy item Callback callback to enable or disable the to file item, depending on the type of object selected. The following code disables the to file item by setting its Enable property off.
12 Code a Programmatic GUI Open a Dialog Box from a Menu Callback The Callback callback for the to file menu item could contain code such as the following to display the standard dialog box for saving files. [file,path] = uiputfile('animinit.m','Save file name'); 'Save file name' is the dialog box title. In the dialog box, the filename field is set to animinit.m, and the filter set to MATLAB language files (*.m). For more information, see the uiputfile reference page.
Examples: Program GUI Components Use of checks when the GUI is first displayed should be consistent with the display. For example, if your GUI has an axes that is visible when a user first opens it and the GUI has a Show axes menu item, be sure to set the menu item’s Checked property on when you create it so that a check appears next to the Show axes menu item initially.
12 Code a Programmatic GUI 2 Click the push tool to display the color selection dialog box and click a color to select it. 3 Click OK on the color selection dialog box. The GUI background color changes to the color you selected—in this case, green.
Examples: Program GUI Components Note Create your own icon with the icon editor described in “Icon Editor” on page 15-63. See the ind2rgb reference page for information on converting a matrix X and corresponding colormap, i.e., an (X, MAP) image, to RGB (truecolor) format. Toggle Tool The toggle tool OnCallback and OffCallback properties specify the toggle tool control actions that occur when the toggle tool is clicked and its State property changes to on or off.
12 Code a Programmatic GUI 1 Copy the following code into a file and save it in your current folder or on your path as toggle_plots.m. Execute the function by typing toggle_plots at the command line. function toggle_plots counter = 0; fh = figure('Position',[250 250 300 340],'Toolbar','none'); ah = axes('Parent',fh,'Units','pixels',... 'Position',[35 85 230 230]); th = uitoolbar('Parent',fh); tth = uitoggletool('Parent',th,'Cdata',rand(20,20,3),... 'OnCallback',@surf_callback,...
Examples: Program GUI Components 12-41
12 Code a Programmatic GUI 2 Click the toggle tool to display the initial plot. The counter increments to 1. 3 Continue clicking the toggle tool to toggle between surf and mesh plots of the peaks data.
13 Manage Application-Defined Data • “Ways to Manage Data in a Programmatic GUI” on page 13-2 • “Share Data Among a GUI’s Callbacks” on page 13-11
13 Manage Application-Defined Data Ways to Manage Data in a Programmatic GUI In this section... “Data Management Mechanism Summary” on page 13-2 “Nested Functions” on page 13-4 “UserData Property” on page 13-5 “Application Data” on page 13-6 “GUI Data” on page 13-8 Data Management Mechanism Summary Most GUIs generate or use data specific to the application. GUI components often need to communicate data to one another and several basic mechanism serve this need.
Ways to Manage Data in a Programmatic GUI Data-Sharing Method How it Works Use for...
13 Manage Application-Defined Data • Nested Functions — Share variables defined at a higher level and call one another when called function is below above, or a sibling of the caller. • UserData Property — A MATLAB workspace variable that you assign to GUI components and retrieve like any other property. • Application Data — Provides a way for applications to save and retrieve data associated with a specified object. For a GUI, this is usually the GUI figure, but it can also be any component.
Ways to Manage Data in a Programmatic GUI See “Share Data with Nested Functions” on page 13-11 for a complete example. UserData Property All GUI components, including menus and the figure itself have a UserData property. You can assign any valid MATLAB workspace value as the UserData property’s value, but only one value can exist at a time. To retrieve the data, a callback must know the handle of the component in which the data is stored.
13 Manage Application-Defined Data See “Share Data with UserData” on page 13-15 for a complete example. Application Data Application data is data that is meaningful to or defined by your application. You attach application data to a figure or any GUI component (other than ActiveX controls) with the functions setappdata and getappdata, The main differences between it and UserData are: • You can assign multiple values to application data, but only one value to UserData.
Ways to Manage Data in a Programmatic GUI Create Application Data Use the setappdata function to create application data. This example generates a 35-by-35 matrix of normally distributed random numbers and creates application data mydata, associated with the figure, to manage it. matrices.rand_35 = randn(35); setappdata(figurehandle,'mydata',matrices); Add Fields to an Application Data Structure Application data is usually defined as a structure to enable you to add fields as necessary.
13 Manage Application-Defined Data GUI Data Most GUIs generate or use data that is specific to the application. These mechanisms provide a way for applications to save and retrieve data stored with the GUI. With GUI data: • You can access the data from within a callback routine using the component’s handle, without needing to find the figure handle. • You do not need to create and maintain a hard-coded name for the data throughout your source code. Use the guidata function to manage GUI data.
Ways to Manage Data in a Programmatic GUI automatically passed to each callback as hObject. See “Specify Callbacks in Function Calls” on page 12-11 for more information. Because there can be only one GUI data variable and it is associated with the figure, you do not need to create and maintain a hard-coded name for the data throughout your source code. Note GUIDE uses GUI data to store its handles structure, and includes it as an argument (called handles) in every callback .
13 Manage Application-Defined Data Note To use hObject, you must specify a component’s callback properties as function handles. When you do, the component handle is automatically passed to each callback as hObject. See “Specify Callbacks in Function Calls” on page 12-11 for more information.
Share Data Among a GUI’s Callbacks Share Data Among a GUI’s Callbacks In this section... “Share Data with Nested Functions” on page 13-11 “Share Data with UserData” on page 13-15 “Share Data with Application Data” on page 13-18 “Share Data with GUI Data” on page 13-21 The following four sections each contain complete code for example GUIs that you can copy to code files and run. For general information about these methods, see “Ways to Manage Data in a Programmatic GUI” on page 13-2.
13 Manage Application-Defined Data The GUI behavior is as follows: • When a user moves the slider, the edit text component displays the slider’s current value and prints a message to the Command Window indicating how far the slider moved from its previous position. You changed the slider value by 24.11 percent.
Share Data Among a GUI’s Callbacks 'Callback',@slider_callback); eth = uicontrol(fh,'Style','edit',... 'String',num2str(get(sh,'Value')),... 'Position',[30 175 240 20],... 'Callback',@edittext_callback); sth = uicontrol(fh,'Style','text','String',... 'Enter a value or click the slider.',... 'Position',[30 215 240 20]); number_errors = 0; previous_val = 0; val = 0; % ------------First Nested Function--------------% Set the value of the edit text component String property % to the value of the slider.
13 Manage Application-Defined Data num2str(number_errors),' times.']); val = previous_val; end end end Because the components are constructed at the top level, their handles are immediately available to the callbacks that are nested at a lower level of the routine. The same is true of the error counter, number_errors, the previous slider value, previous_val, and the new slider value, val. You do not need to pass these variables as arguments.
Share Data Among a GUI’s Callbacks • num2str converts the value to a string. • set sets the String property of the edit text component to the updated value. Edit Text Callback. The callback for edit text, edittext_callback, uses the slider handle, sh, to determine the slider’s Max and Min properties and to set the slider Value property, which determine the position of the slider thumb.
13 Manage Application-Defined Data UserData Property Example: Passing Data Between Components The following code is the same as in the prior example, “Share Data with Nested Functions” on page 13-11, but uses the UserData property to initialize and increment the error counter. It also uses nested functions to provide callbacks with access to other component’s handles, which the main function defines.
Share Data Among a GUI’s Callbacks set(eth,'String',num2str(slider.val)); sprintf('You changed the slider value by %6.2f percent.',... abs(slider.val - slider.previous_val)) % Save slider in UserData before returning. set(eth,'UserData',slider) end % ---------------------------------------------------% Set the slider value to the number the user types in % the edit text or display an error message. function edittext_callback(hObject,eventdata) % Get slider from edit text UserData.
13 Manage Application-Defined Data Slider Values. In this example, both the slider callback, slider_callback and the edit text callback, edittext_callback, retrieve the structure slider from the edit text UserData property. The slider structure holds previous and current values of the slider. The callbacks then save the value slider.val to slider.previous_val before retrieving the new value and assigning it to slider.val.
Share Data Among a GUI’s Callbacks function slider_gui_appdata fh = figure('Position',[250 250 350 350],... 'MenuBar','none','NumberTitle','off',... 'Name','Sharing Data with Application Data'); sh = uicontrol(fh,'Style','slider',... 'Max',100,'Min',0,'Value',25,... 'SliderStep',[0.05 0.2],... 'Position',[300 25 20 300],... 'Callback',@slider_callback); eth = uicontrol(fh,'Style','edit',... 'String',num2str(get(sh,'Value')),... 'Position',[30 175 240 20],...
13 Manage Application-Defined Data slider_data.previous_val = slider_data.val; slider_data.val = str2double(get(hObject,'String')); % Determine whether val is a number between the % slider's Min and Max. If it is, set the slider Value. if isnumeric(slider_data.val) && ... length(slider_data.val) == 1 && ... slider_data.val >= get(sh,'Min') && ... slider_data.val <= get(sh,'Max') set(sh,'Value',slider_data.val); sprintf('You changed the slider value by %6.2f percent.',... abs(slider_data.val - slider_data.
Share Data Among a GUI’s Callbacks Both callbacks use the getappdata and setappdata functions to retrieve and save the slider_data structure as slider application data. Share Data with GUI Data GUI data, which you manage with the guidata function, is accessible to all callbacks of the GUI. A callback for one component can set a value in GUI data, which can then be read by a callback for another component. For more information, see “GUI Data” on page 13-8.
13 Manage Application-Defined Data % ---------------------------------------------------% Set the value of the edit text component String property % to the value of the slider. function slider_callback(hObject,eventdata) slider = guidata(fh); % Get GUI data. slider.previous_val = slider.val; slider.val = get(hObject,'Value'); set(eth,'String',num2str(slider.val)); sprintf('You changed the slider value by %6.2f percent.',... abs(slider.val - slider.
Share Data Among a GUI’s Callbacks Slider Values. In this example, both the slider callback, slider_callback, and the edit text callback, edittext_callback, retrieve the GUI data structure slider which hold previous and current values of the slider. They then save the value, slider.val to slider.previous_val before retrieving the new value and assigning it to slider.val. Before returning, each callback saves the slider structure to GUI data. slider = guidata(fh); % Get GUI data. slider.
13 13-24 Manage Application-Defined Data
14 Manage Callback Execution
14 Manage Callback Execution Callback Sequencing and Interruption In this section...
Callback Sequencing and Interruption Note For information about what callbacks are and do, see “Write Code for Callbacks” on page 12-7 in this User’s Guide and also “Callback Properties for Graphics Objects”. Order of Callback Execution As “Kinds of Callbacks” on page 12-8 describes, interacting with figures and graphic objects can trigger a variety of callbacks. More than one callback can execute in response to a given user action, such as a button or key press.
14 Manage Callback Execution 3 KeyPressFcn (uicontrol and uitable callback) 4 KeyReleaseFcn (in figure window only) 5 WindowKeyReleaseFcn (in figure window or any of its child objects) How the Interruptible Property Works You can set an object’s Interruptible property to either on (the default) or off. If theInterruptible property of the object whose callback is executing is on, the callback can be interrupted.
Callback Sequencing and Interruption - WindowButtonDownFcn WindowButtonMotionFcn WindowButtonUpFcn WindowScrollWheelFcn For callbacks that objects can issue continuously, such as most of the above, setting the figure’s Interruptible property to 'off' might be necessary if callbacks from other objects or GUIs could fire while such interactions are occurring. The rationale is, do not interrupt callbacks that keep on coming unless there is a specific reason to do so.
14 Manage Callback Execution is taken into account only if the Interruptible property of the executing callback’s object is off, i.e., the executing callback is not interruptible.
Callback Sequencing and Interruption This code creates the two Wait buttons and specifies the callbacks that service them. h_interrupt = uicontrol(h_panel1,'Style','pushbutton',... 'Position',[30,110,120,30],... 'String','Wait (interruptible)',... 'Interruptible','on',... 'Callback',@wait_interruptible); h_noninterrupt = uicontrol(h_panel1,'Style','pushbutton',... 'Position',[30,40,120,30],... 'String','Wait (noninterruptible)',... 'Interruptible','off',...
14 Manage Callback Execution This code creates the two plot buttons and specifies the callbacks that service them. hsurf_queue = uicontrol(h_panel2,'Style','pushbutton',... 'Position',[30,200,110,30],... 'String','Surf Plot (queue)',... 'TooltipString','BusyAction = queue',... 'BusyAction','queue',... 'Callback',@surf_queue); hmesh_cancel = uicontrol(h_panel2,'Style','pushbutton',... 'Position',[30,130,110,30],... 'String','Mesh Plot (cancel)',... 'BusyAction','cancel',...
Callback Sequencing and Interruption Note This link executes MATLAB commands and is designed to work within the MATLAB Help browser. If you are reading this online or in a PDF, go to the corresponding section in the MATLAB Help Browser to use the link. To see the interplay of the Interruptible and BusyAction properties: 1 Click one of the Wait buttons in the first GUI. Both buttons create and update a waitbar.
14 Manage Callback Execution % Enable the other push button set(h_noninterrupt,'Enable','on') end The callback first disables the other push button and clears the axes in the second GUI. It then calls the utility function create_update_waitbar to create and update a waitbar. When create_update_waitbar returns, it enables the other button. Click a Plot Button What happens when you click a Plot button depends on which Wait button you clicked first and the BusyAction property of the Plot button.
Callback Sequencing and Interruption h_plot = surf(h_axes2,peaks_data); end View the Complete GUI Code File. If you are reading this in the MATLAB Help browser, click here to display a complete listing of the code used in this example in the MATLAB Editor. Note This link executes MATLAB commands and is designed to work within the MATLAB Help browser. If you are reading this online or in a PDF, go to the corresponding section in the MATLAB Help Browser to use the links.
14 Manage Callback Execution delete the timer before your GUI closes. To start a timer, call its start method. The timer executes its StartFcn, begins counting, and executes its first TimerFcn callback when the period specified by the StartDelay property expires. To halt a timer, call its stop method. Caution Timers are independent objects that operate asynchronously, as do GUIs. A timer callback can change or even delete data used by your GUI code or code it calls.
15 Examples of GUIs Created Programmatically • “Techniques Explored by Programmatic GUI Examples” on page 15-2 • “GUI with Axes, Menu, and Toolbar” on page 15-4 • “GUI that Displays and Graphs Tabular Data” on page 15-19 • “A GUI That Manages List Data” on page 15-33 • “Color Palette” on page 15-51 • “Icon Editor” on page 15-63
15 Examples of GUIs Created Programmatically Techniques Explored by Programmatic GUI Examples The five complete examples that follow illustrate how to create and program GUIs manually: • “GUI with Axes, Menu, and Toolbar” on page 15-4 • “GUI that Displays and Graphs Tabular Data” on page 15-19 • “A GUI That Manages List Data” on page 15-33 • “Color Palette” on page 15-51 • “Icon Editor” on page 15-63 Each example lists and discusses the components and techniques it uses.
Techniques Explored by Programmatic GUI Examples For information about programming specific types of components, see “Examples: Program GUI Components” on page 12-20. For details on available callbacks and how to use them, see “Write Code for Callbacks” on page 12-7.
15 Examples of GUIs Created Programmatically GUI with Axes, Menu, and Toolbar In this section...
GUI with Axes, Menu, and Toolbar When you run the GUI, it initially displays a plot of five random numbers generated by the MATLAB command rand(5) command, as shown in the following figure. You can select other plots in the pop-up menu. Clicking the Update button displays the currently selected plot on the axes. The GUI File menu has three items: • Open displays a dialog from which you can open files on your computer. • Print opens the Print dialog. Clicking Yes in the Print dialog prints the plot.
15 Examples of GUIs Created Programmatically The GUI toolbar has two buttons: • The Open button performs the same function as the Open menu item. It displays a dialog from which you can open files on your computer. • The Print button performs the same function as the Print menu item. It opens the Print dialog. Clicking Yes in the Print dialog prints the plot.
GUI with Axes, Menu, and Toolbar 3 edit iconRead.m or Click here to open the utility iconRead file in the Editor . If you just want to run the GUI and inspect its code, follow these steps: 1 Click here to add the example files to the MATLAB path (only for the current session). 2 Click here to run the axesMenuToolbar GUI. 3 Click here to display the axesMenuToolbar code in the Editor (read-only). 4 Click here to display the utility iconRead file in the Editor (read-only).
15 Examples of GUIs Created Programmatically 'plot(membrane)', @(a)plot(a,membrane); 'surf(peaks)', @(a)surf(a,peaks)}; Because the data is created at the top level of the GUI function, it is available to all callbacks and other functions in the GUI. For information about using anonymous functions, see “Anonymous Functions” . Create the GUI and Its Components Like the data, the components are created at the top level so that their handles are available to all callbacks and other functions in the GUI.
GUI with Axes, Menu, and Toolbar • Setting the HandleVisibility property to callback ensures that the figure can be accessed only from within a GUI callback, and cannot be drawn into or deleted from the command line. • The Color property defines the background color of the figure. In this case, it is set to be the same as the default background color of uicontrol objects, such as the Update push button.
15 Examples of GUIs Created Programmatically See the Axes Properties reference page for information about axes properties and their default values. The Pop-Up Menu The following statement creates the pop-up menu. hPlotsPopupmenu = uicontrol(... % List of available types of plot 'Parent', hMainFigure, ... 'Units','normalized',... 'Position',[0.11 0.85 0.45 0.1],... 'HandleVisibility','callback', ... 'String',mPlotTypes(:,1),...
GUI with Axes, Menu, and Toolbar • For a push button, the String property defines the label on the button. Here it is defined as the string Update. • Setting the Callback property to @hUpdateButtonCallback defines the name of the callback function that services the push button. That is, clicking the push button triggers the execution of the named callback. This callback function is defined later in the script.
15 Examples of GUIs Created Programmatically it the child of the main figure. This statement creates a menu bar in the figure and puts the File menu on it. For each of the menu items, setting its Parent property to the handle of the parent menu, hFileMenu, causes it to appear on the File menu. • For the main menu and each item on it, the Label property defines the strings that appear in the menu.
GUI with Axes, Menu, and Toolbar • The uipushtool function creates the two push buttons on the toolbar. • The uipushtool TooltipString property assigns a tool tip that displays when the GUI user moves the mouse pointer over the button and leaves it there. • The CData property specifies a truecolor image that displays on the button. For these two buttons, the utility iconRead function supplies the image..
15 Examples of GUIs Created Programmatically Define the Callbacks This topic defines the callbacks that service the components of the GUI. Because the callback definitions are at a lower level than the component definitions and the data created for the GUI, they have access to all data and component handles. Although the GUI has six components that are serviced by callbacks, there are only four callback functions. This is because the Open menu item and the Open toolbar button share the same callbacks.
GUI with Axes, Menu, and Toolbar Note MATLAB software automatically passes hUpdateButtonCallback two arguments, hObject and eventdata, because the Update push button component Callback property, @hUpdateButtonCallback, is defined as a function handle. hObject contains the handle of the component that triggered execution of the callback. eventdata is reserved for future use. The function definition line for your callback must account for these two arguments.
15 Examples of GUIs Created Programmatically The hOpenMenuitemCallback function first calls the uigetfile function to open the standard dialog box for retrieving files. This dialog box lists all files having the extension .m. If uigetfile returns a file name, the function then calls the open function to open it. Print Menu Item Callback The hPrintMenuitemCallback function services the Print menu item and the Print toolbar button .
GUI with Axes, Menu, and Toolbar The hPrintMenuitemCallback function calls the printdlg function. This function opens the standard system dialog box for printing the current figure. Your print dialog box might look different than the one shown here. Close Menu Item Callback The hCloseMenuitemCallback function services the Close menu item. It executes when the GUI user selects Close from the File menu.
15 Examples of GUIs Created Programmatically delete(hMainFigure); end The hCloseMenuitemCallback function calls the questdlg function to create and open the question dialog box shown in the following figure. If the user clicks the No button, the callback returns. If the user clicks the Yes button, the callback deletes the GUI. See “Helper Function: Plot the Plot Types” on page 15-18 for a description of the localUpdatePlot function.
GUI that Displays and Graphs Tabular Data GUI that Displays and Graphs Tabular Data In this section...
15 Examples of GUIs Created Programmatically Plot columns Initial prompt uitable with named columns Axes with x- and y-labels The table displays MATLAB sample data (count.dat) containing hourly counts of vehicles passing by at three locations. The example does not provide a way to change the data except by modifying the tableplot.mmain function to read in a different data set and then manually assign appropriate column names and a different title for the plot.
GUI that Displays and Graphs Tabular Data The tableplot main function creates a GUI figure with the following UI components: • A uitable with three columns of data • An axes with a title • Three check boxes for plotting columns of data • Two static text strings Techniques Explored in the tableplot Example The example demonstrates some ways to interact with a uitable and the data it holds: • Extract column names and use them as menu items • Graph specific columns of data • Brush the graph when the user sel
15 Examples of GUIs Created Programmatically UI Object Handle Callback Type Callback Signature Remarks Check box — Callback {@plot_callback,3} Plots a line graph of column 1 data. Markers hmkrs — — Used by table select_callback to brush selected table data on plot. Static text hprompt — — Prompt displayed in axes that disappears when user plots data.
GUI that Displays and Graphs Tabular Data The circle markers appear and disappear dynamically as the user selects cells in the table. You do not need to plot lines in order to display the markers. Lines are individually plotted and removed via the three check boxes. View and Run the tableplot Code If you are reading this example in the MATLAB Help browser, you can access its files by clicking the following links.
15 Examples of GUIs Created Programmatically PDF, go to the corresponding section in the MATLAB Help Browser to use the links. If you intend to modify the layout or code of this GUI example, you should first save a copy of its code in your current folder (You need write access to your current folder to do this.) Click on the following links to copy the example files to your current folder and open them. 1 Click here to copy the tableplot.
GUI that Displays and Graphs Tabular Data The main tableplot function sets up the uitable is immediately after loading a data matrix into the workspace. The table’s size adapts to the matrix size (matrices for uitables must be 1-D or 2-D). % Load some tabular data (traffic counts from somewhere) count = load('count.
15 Examples of GUIs Created Programmatically % Create an axes on the right side; set x and y limits to the % table value extremes, and format labels for the demo data. haxes = axes('Units', 'normalized',... 'Position', [.465 .065 .50 .85],... 'XLim', [0 tablesize(1)],... 'YLim', [0 max(max(count))],... 'XLimMode', 'manual',... 'YLimMode', 'manual',... 'XTickLabel',...
GUI that Displays and Graphs Tabular Data % Callback to erase and replot markers, showing only those % corresponding to user-selected cells in table. % Repeatedly called while user drags across cells of the uitable % hmkrs are handles to lines having markers only set(hmkrs, 'Visible', 'off') % turn them off to begin % Get the list of currently selected table cells sel = eventdata.
15 Examples of GUIs Created Programmatically 3 3 2 3 If rows 5, 6, and 7 of columns 2 and 3 are selected, eventdata = Indices: [6x2 double] sel = 5 5 6 6 7 7 2 3 2 3 2 3 After hiding all the markers, the callback identifies the unique columns selected. Then, iterating over these columns, the row indices for the selection are found; x-values for all row indices that don’t appear in the selection are set to empty. The vector of x-values is used to copy y-values from the table and specify dummy z-values.
GUI that Displays and Graphs Tabular Data • htable — To fetch table data and column names for plotting the data and deleting lines; the column argument identifies which column to draw or erase. • haxes — To draw lines and delete lines from the axes. • hprompt — To remove the prompt (which only displays until the first line is plotted) from the axes. Keying on the column argument, the callback takes the following actions.
15 Examples of GUIs Created Programmatically end end Subfunction Summary for tableplot The tableplot example contains the callbacks listed in the following table, which are discussed in the previous section. Click a function’s name to open it in the Editor window.
GUI that Displays and Graphs Tabular Data • Parse command-line arguments specifying a workspace variable to load into the table when the GUI opens If the user specifies the name of a workspace variable when calling tableplot, its opening function can validate the argument. (Does it exist? Is it numeric? Is it one- or two-dimensional?) If the argument passes these tests, assign the uitable Data property to it and proceed to the next step.
15 Examples of GUIs Created Programmatically The data matrix might have columns with very different data ranges and units of measure. Therefore, one challenge of plotting columns of arbitrary matrices together is to specify appropriate limits for the y-axis. (The x-axis always portrays the row indices.) By default, the axes’ YLim property is 'auto', so that the y-limits adjust to span the minimum and maximum of the data being plotted.
A GUI That Manages List Data A GUI That Manages List Data In this section...
15 Examples of GUIs Created Programmatically An empty List Master GUI A List Master GUI with Controls and Data The Components A new List Master GUI figure contains a File menu, containing items to open or create a List Master GUI, import and export data, save the GUI and close it, as shown on the left side of the preceding illustration. Menu items are enabled and disabled as appropriate.
A GUI That Manages List Data - - A list box, displaying an imported list Three push buttons that respectively • Move the selected item higher in the current list • Move the selected item lower in the current list • Delete the selected item from the list A check box to control whether list items are numbers or not An “edit panel” containing • A text box for editing the current list item • Radio buttons specifying how edits should be handled (Replace or Add) The list box always has one and only o
15 Examples of GUIs Created Programmatically • Automatically number list items and renumber them as needed (or not) • Give several uicontrols the same callback and invoke callbacks from other functions View and Run the List Master Code The List Master example includes one code file, two MAT-files and a text file: • listmaster.m — The GUI code file, containing all required subfunctions • listmaster_icons.mat — Three icons, used as CData for push buttons • senators110cong.
A GUI That Manages List Data If you just want to run the GUI and inspect its code, follow these steps: 1 Click here to add the example files to the MATLAB path (only for the current session). 2 Click here to run the listmaster GUI. 3 edit listmaster.m or Click here to display the GUI code file in the Editor (read-only). 4 edit senators110th.txt or Click here to display the senators110th.txt sample data file in the MATLAB Editor.
15 Examples of GUIs Created Programmatically 3 Type a name for the list you want to create and click OK. If you want to use the sample data provided with this example, you can call the list something like US Senate Phone Book, as shown on the left side of the following figure. (List Master restricts list names to 32 characters or fewer). The New menu item’s callback, lmnew, labels the figure and creates the GUI’s controls, beginning with a uipanel.
A GUI That Manages List Data Figure name Panel with list name Selected list item List box Move item down up Toggle list Delete list item numbering Edit mode Editable list item Because the positions of all controls are specified with normalized Units, the GUI is resizable; only the button icons and the text fonts are of fixed size. Import Data into List Master You can import data into a List Master GUI at any time. If the GUI already contains data, the data you import replaces it.
15 Examples of GUIs Created Programmatically Note A List Master GUI has no facility to rename itself should someone replace its contents. You can easily add such a feature; see “Add a “Rename List” Option to List Master” on page 15-50. You can import into the GUI text from a cell array in the MATLAB workspace. Each element of the cell array should contain a line of text corresponding to a single list item.
A GUI That Manages List Data 1 Click on the list box item you want to copy or select the item’s text in the edit box. 2 Type Ctrl+C to copy the item. 3 Open a document into which you want to paste the item 4 Place the cursor where you want to paste the item and type Ctrl+V. The item appears in the external document. You can also copy a string from another document and paste into the text edit box. (However, all Return and Tab characters the string might have are lost.
15 Examples of GUIs Created Programmatically Program List Master The List Master GUI code file contains 22 functions, organized into five groups. • “List Master Main Program” on page 15-42 • “List Master Setup Functions” on page 15-44 • “List Master Menu Callbacks” on page 15-45 • “List Master List Callbacks” on page 15-47 • “List Master Utility Functions” on page 15-48 List Master Main Program The main function, listmaster, opens a figure in portrait format near the center of the screen.
A GUI That Manages List Data Menu Item How Used Callback Save as... Saves current List Master to a different FIG-file lmsaveas Quit Exits List Master, with option to save first lmquit After you create a blank GUI with its File menu, the listmaster function exits. The main function sets up the figure as follows: fh = figure('MenuBar','none', ... 'NumberTitle','off', ... 'Name','ListMaster', ... 'Tag','lmfigtag', ... 'CloseRequestFcn', @lmquit, ... 'Units','pixels', ...
15 Examples of GUIs Created Programmatically GUI. If the Tag has any other value, the program closes the figure and displays an error alert. The Quit menu option closes the GUI after checking whether the figure needs to be saved. If the contents have changed, its callback (lmquit) calls the lmsaveas callback to give the user an opportunity to save. The figure’s CloseRequestFcn also uses the lmquit callback when the user clicks the figure’s close box.
A GUI That Manages List Data buttons that migrate items higher or lower in the list box. It disables the Move Up button when the selected item is at the top of the list, and disables the Move Down button when the selected item is at the bottom of the list. Then it copies the current list selection into the edit text box, replacing whatever was there. Finally, it sets the “dirty” flag in the figure’s application data to indicate that the GUI’s data or state has changed.
15 Examples of GUIs Created Programmatically Called from a blank GUI, the function requests a name, and then populates the figure with all controls. Called from a GUI that contains a list, lmnew calls the main listmaster function to create a new GUI, and uses that figure’s handle (instead of its own) when populating it with controls.
A GUI That Manages List Data List Master List Callbacks The six callbacks not associated with menu items are listed and described below. Click any callback to view it in the MATLAB Editor. The function opens from the Creating Graphical Interfaces examples folder.
15 Examples of GUIs Created Programmatically % Get the figure handle and from that, the listbox handle fh = ancestor(hObject,'figure'); lh = findobj(fh,'Tag','lmtablisttag1'); Here, hObject is whatever object issued the callback that is currently executing, and 'lmtablisttag1' is the hard-coded Tag property of the list box. Always looking up the figure handle with ancestor assures that the current List Master is identified.
A GUI That Manages List Data Utility Function How Used isguidirty Returns logical state of the figure’s dirty flag make_list_output_name Converts the name of a list (obtained from the figure Name property) into a valid MATLAB identifier, which serves as a default when saving the GUI or exporting its data List numbering works by adding five spaces before each list entry, then substituting numerals for characters 3, 2, and 1 of these blanks (as needed to display the digits) and placing a period in char
15 Examples of GUIs Created Programmatically Note Use application data to communicate information between uicontrols and other objects in GUIs you create. You can assign application data to any Handle Graphics object. The data can be of any type, and is separate from that of other objects. Application data is not an object property on which set or get operates; you must use function setappdata to store it and function getappdata to retrieve it.
Color Palette Color Palette In this section...
15 Examples of GUIs Created Programmatically The colorPalette function populates a GUI figure or panel with a color palette. See “View and Run the Color Palette Code” on page 15-55 for a link to the code file comprising this example. The figure below shows the palette as the child of a figure.
Color Palette • A More Colors push button • A preview of the selected color, below the color cells, defined as a text component • Text components to specify the red, blue, and green color values Use the Color Palette These are the basic steps for using the color palette. 1 Clicking a color cell toggle button: • Displays the selected color in the preview area. • The red, green, and blue values for the newly selected color are displayed in the R, G, and B fields to the right of the preview area.
15 Examples of GUIs Created Programmatically Call the colorPalette Function You can call the colorPalette function with a statement such as mGetColorFcn = colorPalette('Parent',hPaletteContainer) The colorPalette function accepts property value pairs as input arguments. Only the custom property Parent is supported. This property specifies the handle of the parent figure or panel that contains the color palette. If the call to colorPalette does not specify a parent, it uses the current figure, gcf.
Color Palette Techniques Used in the Color Palette Example This example illustrates the following techniques: • Retrieving output from the GUI when it returns. • Supporting custom input property/value pairs with data validation. • Sharing data between two GUIs See “Icon Editor” on page 15-63 for examples of these and other programming techniques. Note This example uses nested functions. For information about using nested functions, see “Nested Functions”.
15 Examples of GUIs Created Programmatically 3 Click here to display the GUI code file in the Editor (read-only). Note Do not save GUI files to the examples folder where you found them, or you will overwrite the original files. Save them to your current or other folder that you work in. Subfunction Summary for Color Palette The color palette example includes the callbacks listed in the following table.
Color Palette The example also includes the helper functions listed in the following table. Function Description layoutComponent Dynamically creates the Eraser tool and the color cells in the palette. It calls localDefineLayout. localUpdateColor Updates the preview of the selected color. getSelectedColor Returns the currently selected color which is then returned to the colorPalette caller. localDefineLayout Calculates the preferred color cell and tool sizes for the GUI.
15 Examples of GUIs Created Programmatically 7 Callback definitions. These callbacks, which service the GUI components, are subfunctions of the colorPalette function and so have access to the data and component handles created at the top level, without their having to be passed as arguments. 8 Helper function definitions.
Color Palette The colorPalette function then defines the valid custom properties in a 3-by-3 cell array. mPropertyDefs = {... % The supported custom property/value % pairs of this GUI 'parent', @localValidateInput, 'mPaletteParent'; • The first column contains the property name. • The second column contains a function handle for the function, localValidateInput, that validates the input property values. • The third column is the local variable that holds the value of the property.
15 Examples of GUIs Created Programmatically Pass Output to a Caller on Returning If a host GUI calls the colorPalette function with an output argument, it returns a function handle that the host GUI can call to get the currently selected color. The host GUI calls colorPalette only once. The call creates the color palette in the specified parent and then returns the function handle. The host GUI can call the returned function at any time before the color palette is destroyed.
Color Palette Just before returning, colorPalette assigns mOutputArgs the function handle for its getSelectedColor helper function and then assigns mOutputArgs to varargout to return the arguments. % Return user defined output if it is requested mOutputArgs{1} =@getSelectedColor; if nargout>0 [varargout{1:nargout}] = mOutputArgs{:}; end The iconEditor executes the colorPalette’s getSeclectedColor function whenever it invokes the function that colorPalette returns to it.
15 Examples of GUIs Created Programmatically y = ceil(pt(1,2)); color = mGetColorFcn(); % update color of the selected block mIconCData(y, x,:) = color; localUpdateIconPlot(); end end 15-62
Icon Editor Icon Editor In this section... “About the Icon Editor Example” on page 15-63 “View and Run the Icon Editor Code” on page 15-65 “Subfunction Summary” on page 15-68 “Code File Organization” on page 15-70 “GUI Programming Techniques” on page 15-70 About the Icon Editor Example This example creates a GUI that enables its user to create or edit an icon. See “View and Run the Icon Editor Code” on page 15-65 for links to the files comprising this example.
15 Examples of GUIs Created Programmatically Icon Editor GUI Components The GUI includes the following components: • An edit text box that instructs the user or contains the name of the file to be edited. The edit text is labeled using a static text. • A push button to the right of the edit text enables the user to select an existing icon file for editing. • A panel containing an axes. The axes displays a 16-by-16 grid for drawing an icon.
Icon Editor • A panel, configured as a line, that separates the icon editor from the OK and Cancel buttons. • An OK push button that causes the GUI to return the icon as an m-by-n-by-3 array and closes the GUI. • A Cancel push button that closes the GUI without returning the icon. Techniques Used in the Icon Editor Example This example illustrates the following GUI programming techniques: • Creating a GUI that does not return a value until the user makes a choice.
15 Examples of GUIs Created Programmatically PDF, go to the corresponding section in the MATLAB Help Browser to use the links. If you intend to modify the layout or code of this GUI example, you should first save a copy of its code in your current folder (You need write access to your current folder to do this.) Click on the following links to copy the example files to your current folder and open them. 1 Click here to copy the four files to your current folder 2 edit iconEditor.
Icon Editor Note Do not save GUI files to the examples folder where you found them, or you will overwrite the original files. Save them to your current or other folder that you work in.
15 Examples of GUIs Created Programmatically Subfunction Summary The icon editor example includes the callbacks listed in the following table. Function Description hMainFigureWindowButtonDownFcn Executes when the user clicks a mouse button anywhere in the GUI figure. It calls localEditColor. hMainFigureWindowButtonUpFcn Executes when the user releases the mouse button. hMainFigureWindowButtonMotionFcn Executes when the user drags the mouse anywhere in the figure with a button pressed.
Icon Editor Function Description localEditColor Changes the color of an icon data point to the currently selected color. Call the function mGetColorFcn returned by the colorPalette function. It also calls localUpdateIconPlot. localUpdateIconPlot Updates the icon preview. It also updates the axes when an icon is read from a file. processUserInputs Determines if the property in a property/value pair is supported. It calls localValidateInput.
15 Examples of GUIs Created Programmatically Code File Organization The iconEditor is programmed using nested functions. Its code is organized in the following sequence: 1 Comments displayed in response to the help command. 2 Data creation. Because the example uses nested functions, defining this data at the top level makes the data accessible to all functions without having to pass them as arguments. 3 GUI figure and component creation. 4 Command line input processing. 5 GUI initialization.
Icon Editor • “Retrieve Output on Return from a GUI” on page 15-73 • “Protect a GUI from Inadvertent Access” on page 15-74 • “Run a GUI on Multiple Platforms” on page 15-75 • “Make a GUI Modal” on page 15-76 • “Share Data Between Two GUIs” on page 15-77 • “Achieve Proper Resize Behavior” on page 15-78 Return Only After the User Makes a Choice At the end of the initialization code, and just before returning, iconEditor calls uiwait with the handle of the main figure to make the GUI blocking.
15 Examples of GUIs Created Programmatically When the user clicks the Cancel button, its callback, hOCancelButtonCallback, effectively deletes the icon data then calls uiresume. This enables the code file to resume execution where it stopped but it returns a null matrix. function hCancelButtonCallback(hObject, eventdata) % Callback called when the Cancel button is pressed mIconCData =[]; uiresume; delete(hMainFigure); end Pass Input Arguments to a GUI Inputs to the GUI are custom property/value pairs.
Icon Editor mIconWidth = 16; % Use input property 'iconwidth' to initialize mIconHeight = 16; % Use input property 'iconheight' to initialize mIconFile = fullfile(matlabroot,'/toolbox/matlab/icons/'); The values of mIconWidth and mIconHeight are interpreted as pixels. The fullfile function builds a full file name from parts. Process the Input Arguments. The processUserInputs helper function processes the input property/value pairs.
15 Examples of GUIs Created Programmatically mOutputArgs{} =mIconCData; if nargout>0 [varargout{1:nargout}] = mOutputArgs{:}; end This code is the last that iconEditor executes before returning. It executes only after clicking the OK or Cancel button triggers execution of hOKButtonCallback or hCancelButtonCallback, which call uiresume to resume execution.
Icon Editor Run a GUI on Multiple Platforms The prepareLayout utility function sets various properties of all the GUI components to enable the GUI to retain the correct look and feel on multiple platforms. Code in the initialization section of iconEditor calls prepareLayout with the handle of the main figure.
15 Examples of GUIs Created Programmatically Select Units. The prepareLayout function decides what units to use based on the GUI’s resizability. It uses strcmpi to determine the value of the GUI’s Resize property. Depending on the outcome, it sets the Units properties of all the objects to either Normalized or Characters. % Make the GUI run properly across multiple platforms by using % the proper units if strcmpi(get(topContainer, 'Resize'),'on') set(allObjects(isprop(allObjects,'Units')),...
Icon Editor Share Data Between Two GUIs The iconEditor embeds a GUI, the colorPalette, to enable the user to select colors for the icon cells. The colorPalette returns the selected color to the iconEditor via a function handle. The colorPalette GUI. Like the iconEditor, the colorPalette defines a cell array, mOutputArgs, to hold its output arguments.
15 Examples of GUIs Created Programmatically The iconEditor’s localEditColor helper function calls mGetColorFcn, the function returned by colorPalette, to execute the colorPalette’s getSelectedColor function.
Icon Editor if strcmpi(get(topContainer, 'Resize'),'on') set(allObjects(isprop(allObjects,'Units')),... 'Units','Normalized'); else set(allObjects(isprop(allObjects,'Units')),... 'Units','Characters'); end Note The iconEditor is resizable because it accepts the default value, on, of the figure Resize property. Resizable Figure. Normalized units map the lower-left corner of the figure and of each component to (0,0) and the upper-right corner to (1.0,1.0).
15 15-80 Examples of GUIs Created Programmatically
A Examples Use this list to find examples in the documentation.
A Examples Simple Examples (GUIDE) “About the Simple GUIDE GUI Example” on page 2-9 “Use a Modal Dialog Box to Confirm an Operation (GUIDE)” on page 10-98 “Time Data Updates from a GUI (GUIDE)” on page 10-105 A-2
Simple Examples (Programmatic) Simple Examples (Programmatic) “About the Simple Programmatic GUI Example” on page 3-2 A-3
A Examples Application Examples (GUIDE) “A Working GUI with Many Components” on page 6-23 “GUI with Multiple Axes (GUIDE)” on page 10-2 “GUI for Animating a 3-D View (GUIDE)” on page 10-15 “GUI to Interactively Explore Data in a Table (GUIDE)” on page 10-31 “List Box Directory Reader (GUIDE)” on page 10-54 “Access Workspace Variables from a List Box (GUIDE)” on page 10-61 “A GUI to Set Simulink Model Parameters (GUIDE)” on page 10-66 “An Address Book Reader (GUIDE)” on page 10-81 A-4
Programming GUI Components (GUIDE) Programming GUI Components (GUIDE) “Push Button” on page 8-30 “Toggle Button” on page 8-31 “Radio Button” on page 8-32 “Check Box” on page 8-33 “Edit Text” on page 8-33 “Slider” on page 8-36 “List Box” on page 8-36 “Pop-Up Menu” on page 8-37 “Panel” on page 8-38 “Button Group” on page 8-42 “Axes” on page 8-45 “ActiveX Control” on page 8-49 “Menu Item” on page 8-59 A-5
A Examples Application-Defined Data (GUIDE) “Sharing Data with UserData” on page 9-11 “Sharing Data with Application Data” on page 9-14 “Sharing Data with GUI Data” on page 9-17 “Example — Manipulating a Modal Dialog Box for User Input” on page 9-22 “Example — Individual GUIDE GUIs Cooperating as Icon Manipulation Tools” on page 9-30 A-6
GUI Layout (Programmatic) GUI Layout (Programmatic) “File Template” on page 11-4 “Check Box” on page 11-15 “Edit Text” on page 11-17 “List Box” on page 11-20 “Pop-Up Menu” on page 11-22 “Table” on page 11-24 “Push Button” on page 11-25 “Radio Button” on page 11-27 “Slider” on page 11-28 “Static Text” on page 11-30 “Toggle Button” on page 11-31 “Panel” on page 11-35 “Button Group” on page 11-36 “Add Axes” on page 11-38 “Add ActiveX Controls” on page 11-41 A-7
A Examples Programming GUI Components (Programmatic) “Check Box” on page 12-21 “Edit Text” on page 12-21 “List Box” on page 12-23 “Pop-Up Menu” on page 12-24 “Push Button” on page 12-25 “Radio Button” on page 12-26 “Slider” on page 12-26 “Toggle Button” on page 12-27 “Panel” on page 12-28 “Button Group” on page 12-28 “Program Axes” on page 12-31 “Program ActiveX Controls” on page 12-34 “Program Menu Items” on page 12-34 “Program Toolbar Tools” on page 12-37 A-8
Application-Defined Data (Programmatic) Application-Defined Data (Programmatic) “Nested Functions Example: Passing Data Between Components” on page 13-11 “UserData Property Example: Passing Data Between Components” on page 13-16 “Application Data Example: Passing Data Between Components” on page 13-18 “GUI Data Example: Passing Data Between Components” on page 13-21 A-9
A Examples Application Examples (Programmatic) “GUI with Axes, Menu, and Toolbar” on page 15-4 “GUI that Displays and Graphs Tabular Data” on page 15-19 “A GUI That Manages List Data” on page 15-33 “Color Palette” on page 15-51 “Icon Editor” on page 15-63 A-10
Index A Index ActiveX controls adding to GUI layout 6-77 programming 8-49 12-34 aligning components in GUIDE 6-89 Alignment Objects Tool GUIDE 6-89 application data appdata functions 9-5 13-6 application-defined data application data 9-5 13-6 GUI data 9-7 13-8 in GUIDE GUIs 9-1 UserData property 9-5 13-5 axes designating as current 8-48 multiple in GUI 10-2 10-15 axes, plotting when hidden 10-76 B background color system standard for GUIs 6-138 11-95 backward compatibility GUIs to Version 6 5-4 button gro
Index context menus associating with an object 6-120 creating in GUIDE 6-101 creating with GUIDE 6-114 menu items 6-116 parent menu 6-114 cross-platform compatibility GUI background color 6-138 11-95 GUI design 6-137 GUI fonts 6-137 11-94 GUI units 6-139 11-96 D data sharing among GUI callbacks 9-10 default system font in GUIs 6-137 11-94 dialog box modal 10-98 E edit box setting fonts of 11-18 edit text 8-33 12-21 edit text input validation of 8-34 exporting a GUI confirmation 5-2 F FIG-file generate i
Index listmaster 15-33 tableplot 15-19 GUI export confirmation 5-2 GUI FIG-files opening 10-60 GUI files in GUIDE 7-2 GUI initialization controlling for singleton 9-9 GUI layout in GUIDE copying components 6-81 cutting and clearing components 6-81 moving components 6-83 pasting and duplicating components 6-81 selecting components 6-80 GUI object hierarchy viewing in GUIDE 6-136 GUI options (GUIDE) function prototypes 5-12 singleton 5-12 system color background 5-12 GUI singleton initialization of 9-9 GUI s
Index interrupting callback example of 10-22 in GUIDE 7-2 NextPlot problems with in GUIs 11-41 L Layout Editor show component names 5-7 Layout Editor window show file extension 5-7 show file path 5-7 list boxes 8-36 12-23 example 10-54 listmaster GUI example about 15-33 accessing 15-36 operating 15-37 programming 15-42 techniques used 15-35 M menu item check 8-61 12-36 menus callbacks 8-59 12-34 context menus in GUIDE 6-114 creating in GUIDE 6-101 drop-down menus 6-102 menu bar menus 6-102 menu items 6
Index creating in GUIDE 6-114 singleton GUI defined 5-13 GUIDE option 5-12 size of GUI setting with GUIDE 6-15 sliders 6-21 11-12 status bar show in GUIDE Layout Editor 6-18 system color background GUIDE option 5-12 T tab order components in GUIDE 6-98 Tab Order Editor 6-98 Table Property Editor 6-69 tables for GUIs 6-66 Tag property assigning in GUIDE 6-37 template for GUI selecting in GUIDE 6-6 toggle buttons 8-31 12-27 toolbar show in GUIDE Layout Editor 6-18 Toolbar Editor using 6-124 toolbar menus c