ComputationVisualizationProgrammingCreating Graphical User InterfacesVersion 1MATLAB®The Language of Technical Computing
1 Getting Started with GUIDE1-2This section illustrates the process of using GUIDE to create GUIs:•GUI Development Environment – overview of the layou
3 GUIDE Layout Tools3-30Opening FIG-FilesYou can use the open, openfig, and hgload commands to open a file having a .fig extension. The application M-
4Programming GUIsGUI Programming Topics . . . . . . . . . . . . . . 4-2Understanding the Application M-File . . .
4 Programming GUIs4-2GUI Programming TopicsGraphical user interfaces (GUIs) contain various user-interface components that enable software to communic
Understanding the Application M-File4-3Understanding the Application M-FileMATLAB generates the application M-file to provide a framework for the prog
4 Programming GUIs4-4•Execution Paths in the Application M-File•Initializing the GUI•Managing GUI Data with the Handles StructureExecution Paths in th
Understanding the Application M-File4-5catchdisp(lasterr);endendAny output arguments returned by your callback subfunction are then returned though th
4 Programming GUIs4-6If no arguments launch GUICall application M-fileApplication M-File Execution PathCheck input argumentsYesNoOpen figureFigure exi
Understanding the Application M-File4-7Initializing the GUIThe application M-file automatically includes some useful techniques for managing the GUI.
4 Programming GUIs4-8Positioning the GUI OnscreenThe application M-file uses the movegui command to ensure the GUI figure is visible on the screen of
Understanding the Application M-File4-9The handles structure is one of the arguments passed to each callback. You can also use this same structure to
GUIDE – GUI Development Environment1-3GUIDE – GUI Development EnvironmentGUIDE, MATLAB’s Graphical User Interface development environment, provides a
4 Programming GUIs4-10Managing GUI Data with the Handles StructureGUIDE provides a mechanism for storing and retrieving global data using the same str
Managing GUI Data with the Handles Structure4-11Defining the Data Fields During InitializationThe following excerpt from the GUI setup code show two a
4 Programming GUIs4-12else% Increment the error count, and display ithandles.numberOfErrors = handles.numberOfErrors+1;set(handles.edit1,'String&
Managing GUI Data with the Handles Structure4-13•Retrieving the structure within the subfunction when it is required.Using the guidata Function withou
4 Programming GUIs4-14Application-Defined DataApplication-defined data provides a way for applications to save and retrieve data stored with the GUI.
Designing for Cross-Platform Compatibility4-15Designing for Cross-Platform CompatibilityYou can use specific property settings to create a GUI that be
4 Programming GUIs4-16Specifying a Fixed-Width FontIf you want to use a fixed-width font for a uicontrol, set its FontName property to the string fixe
Designing for Cross-Platform Compatibility4-17on UNIX). When your GUI is deployed on a different platform, it uses that computer’s standard color. Thi
4 Programming GUIs4-18Types of CallbacksThe primary mechanism for implementing a GUI is programming the callback of the uicontrol objects used to buil
Types of Callbacks4-19•WindowButtonUpFcn – MATLAB executes the specified callback when users release the mouse button, after having pressed the mouse
1 Getting Started with GUIDE1-4GUIDE ToolsetThe following links provide more information on the full set of GUIDE development tools.•Layout Editor – a
4 Programming GUIs4-20Interrupting Executing CallbacksBy default, MATLAB allows an executing callback to be interrupted by subsequently invoked callba
Interrupting Executing Callbacks4-21•drawnow•figure •getframe•pause•waitforWhen MATLAB encounters one of these commands in a callback, it suspends exe
4 Programming GUIs4-222 If the event at the top of the queue calls for a figure window redraw, MATLAB performs the redraw and proceeds to the next eve
Controlling GUI Figure Window Behavior4-23Controlling GUI Figure Window BehaviorWhen designing a GUI you need to consider how you want the figure wind
4 Programming GUIs4-24Making a GUI Figure ModalSet the GUI figure’s WindowStyle property to modal to make the window modal. You can use the Property I
5Application ExamplesExamples of Application Techniques . . . . . . . . . 5-2GUI with Multiple Axes . . . . . . . .
5 Application Examples5-2Examples of Application TechniquesThis section contains a series of examples that illustrate techniques that are useful for i
GUI with Multiple Axes5-3GUI with Multiple AxesThis example creates a GUI that contains two axes for plotting data. For simplicity, this example obtai
5 Application Examples5-4View the Layout and Application M-FileUse the following links to display the GUIDE Layout Editor and the MATLAB Editor with a
GUI with Multiple Axes5-5Identifying the AxesSince there are two axes in this GUI, you must be able to specify which one you want to target when you i
Getting Started Example1-5Getting Started ExampleThis example shows how to create a GUI using GUIDE. It illustrates the process you should follow when
5 Application Examples5-6For example, the Tag of the axes used to display the FFT is set to frequency_axes. Therefore, within a callback, you access i
GUI with Multiple Axes5-7Callback Accessibility of Object Handles. When GUIs include axes, handles should be visible from within callbacks. This enabl
5 Application Examples5-8•Making the appropriate axes current using the axes command and the handle of the axes. For example,axes(handles.frequency_ax
Launching a Dialog to Confirm an Operation5-9Launching a Dialog to Confirm an OperationThis example illustrates how to display a dialog when users att
5 Application Examples5-10•Handle the case where the user closes the dialog from the window manager close box without responding.The following section
Launching a Dialog to Confirm an Operation5-11Making the Dialog ModalTo make the dialog modal, select the figure in the Layout Editor and right-click
5 Application Examples5-123 Once the user makes a choice, the confirmation dialog callbacks resume execution and return a value to the Close button ca
Launching a Dialog to Confirm an Operation5-13•One numeric argument – launch the dialog and place it at the location specified in a two-element vector
5 Application Examples5-14Specify the Location of the DialogThe dialog M-file accepts an input argument that specifies where to display the dialog. Th
Launching a Dialog to Confirm an Operation5-15•The No button callback executes uiresume after setting handles.answer to 'no'.uiwait(fig);if
1 Getting Started with GUIDE1-6The popup menu contains three strings – “peaks”, “membrane”, and “sinc”, which enable the user to select the data to pl
5 Application Examples5-16uiresume(handles.figure1);function varargout = yesButton_Callback(h, eventdata, handles, varargin)handles.answer = 'yes
Launching a Dialog to Confirm an Operation5-17Select Edit CloseRequestFcn from the context menu. GUIDE automatically places a new subfunction in the a
5 Application Examples5-18List Box Directory ReaderThis example uses a list box to display the files in a directory. When the user double clicks on a
List Box Directory Reader5-19Note The following links execute MATLAB commands and are designed to work within the MATLAB Help browser. The first link
5 Application Examples5-20The following code listing show the entire initialization section of the application M-file. The statements in bold are the
List Box Directory Reader5-21Loading the List BoxThis example creates a subfunction to load items into the list box. This subfunction accepts the path
5 Application Examples5-22The List Box CallbackThe list box callback handles only one case: a double click on an item. Double clicking is the standard
List Box Directory Reader5-23The open statement is called within a try/catch block to capture errors in an error dialog (errordlg), instead of returni
5 Application Examples5-24Accessing Workspace Variables from a List BoxThis GUI uses a list box to display workspace variables, which the user can the
Accessing Workspace Variables from a List Box5-25•Delete the string assigned to the list box Callback property.View the Layout and Application M-FileU
Getting Started Example1-7Note The following links execute MATLAB commands and are designed to work within the MATLAB Help browser. The first link ad
5 Application Examples5-26Reading the Selections from the List BoxThis GUI requires the user to select two variables from the workspace and then choos
Accessing Workspace Variables from a List Box5-27var1 = list_entries{index_selected(1)};var2 = list_entries{index_selected(2)};end Callbacks for the P
5 Application Examples5-28A GUI to Set Simulink Model Parameters This example illustrates how to create a GUI that sets the parameters of a Simulink m
A GUI to Set Simulink Model Parameters5-29assembled to create the GUI. You can also see a complete listing of the code that is discussed in the follow
5 Application Examples5-30Plotting the ResultsYou can generate a plot of one or more simulation results by selecting the row of results (Run1, Run2, e
A GUI to Set Simulink Model Parameters5-31•Change the size of the controller Gain block so it can display the gain value (set_param).•Bring the GUI fo
5 Application Examples5-32•Sets the value of the Current value edit text component to match the slider.•Sets the appropriate block parameter to the ne
A GUI to Set Simulink Model Parameters5-33model_open(handles)% Get the new value for the Kf GainNewStrVal = get(h,'String');NewVal = str2dou
5 Application Examples5-34ResultsData = handles.ResultsData;% Determine the maximum run number currently used.maxNum = ResultsData(length(ResultsData)
A GUI to Set Simulink Model Parameters5-35structure. When a user clicks on the Remove button, the callback executes the following steps:•Determines wh
1 Getting Started with GUIDE1-8If you want to set the size of the GUI to an exact value, set the Position property using the Property Inspector (selec
5 Application Examples5-36•Collects the data for each run selected in the Results list, including two variables (time vector and output vector) and a
A GUI to Set Simulink Model Parameters5-37PlotData{ctVal*3} = plotColor{numColor};legendStr{ctVal} = [handles.ResultsData(currentVal(ctVal)).RunName,.
5 Application Examples5-38Closing the GUIThe GUI Close button callback closes the plot figure, if one exists and then closes the GUI. The handle of th
A GUI to Set Simulink Model Parameters5-39See the description of list boxes for more information on how to trigger the list box callback.
5 Application Examples5-40An Address Book ReaderThis example shows how to implement a GUI that displays names and phone numbers, which it reads from a
An Address Book Reader5-41•The names and phone numbers stored in the MAT-file.•An index pointer that indicates the current name and phone number, whic
5 Application Examples5-42•Application M-file options selected: Generate callback function prototypesApplication allows only one instance to runLaunch
An Address Book Reader5-43catchdisp(lasterr);endendLoading an Address Book Into the ReaderThere are two ways in which an address book (i.e., a MAT-fil
5 Application Examples5-44% If called without any file then set file to the default file name.% Otherwise if the file exists then load it.if isempty(f
An Address Book Reader5-45(uigetfile) that enables the user to browser for files. The dialog displays only MAT-files, but users can change the filter
Getting Started Example1-92. Add the ComponentsSelect the components to add from the palette and drag them into the layout area. You can resize compon
5 Application Examples5-46Storing and Retrieving DataThis callback makes use of the handles structure to access the contents of the address book and t
An Address Book Reader5-47'Yes','Cancel','Yes');switch Answercase 'Yes'Addresses(end+1).Name = Current_Name; %
5 Application Examples5-48Addresses = handles.Addresses;Answer=questdlg('Do you want to change the phone number?', ...'Change Phone Num
An Address Book Reader5-49button Callback string includes 'Next' as the last argument. The value of str is used in case statements to implem
5 Application Examples5-50set(handles.Contact_Name,'string',Current_Name)set(handles.Contact_Phone,'string',Current_Phone)% Update
An Address Book Reader5-51Save_Callback Code Listingfunction varargout = Save_Callback(h, eventdata, handles, varargin)% Get the Tag of the menu selec
5 Application Examples5-52The Address Book Resize FunctionThe address book defines it’s own resize function. To use this resize function, you must set
An Address Book Reader5-53original position of the GUI on screen. Therefore, the resize function applies a compensation to the vertical position (seco
5 Application Examples5-54% Adjust the size of the Contact Name text box% Set the units of the Contact Name field to 'Normalized'set(handles
I-1IndexAactivate figure 3-5aligning GUI components 3-10Alignment Tool, for GUIs 3-10application data 4-14application M-file 2-3, 4-3application optio
1 Getting Started with GUIDE1-103. Align the ObjectsTo align components with respect to one another, select Align Objects from the Tools menu. The Ali
IndexI-2waiting for user input 2-20guide 3-2GUIs, saving 3-29Hhandles structure 4-10handles structure in GUIs 4-8help button for GUIs 5-37hidden figur
Getting Started Example1-114. Set Properties for Each ComponentTo set the properties of each component, select the Property Inspector from the View me
How to Contact The MathWorks:www.mathworks.com Webcomp.soft-sys.matlab [email protected] Technical [email protected] Product
1 Getting Started with GUIDE1-12Popup Menu ItemsEach item in the popup menu list needs to be on a separate line in the String property edit box:
Getting Started Example1-13Tag and Callback PropertiesWhen you first add a component to the layout, its Callback property is set to the string <aut
1 Getting Started with GUIDE1-14When you save or activate the GUI, GUIDE converts this string to one that calls the callback subfunction in the genera
Getting Started Example1-15This example sets the popup menu Tag to data_popup, resulting in the name data_popup_Callback for the popup menu’s callback
1 Getting Started with GUIDE1-165. Activate the GUIActivate the GUI by selecting Activate Figure from the Tools menu or use the activator button from
Getting Started Example1-17write the callbacks – the functions that execute when users activate a component in the GUI. The application M-file:•Initia
1 Getting Started with GUIDE1-18•Managing GUI DataPopup Menu CallbackThe popup menu enables users to select the data to plot. For simplicity, this exa
Getting Started Example1-19data_popup_Callback(handles.data_popup,[],handles)Push Button CallbacksEach of the push buttons creates a different type of
1 Getting Started with GUIDE1-20Example – Adding the File Menu to the GUIThe GUI has a File menu with two menu items:•Print – sends the plot to the us
Getting Started Example1-212. Set the Label and TagSet the Label property to the word File. This is the name of the menu as it appears on the GUI menu
iContents1Getting Started with GUIDEGUIDE – GUI Development Environment . . . . . . . . . . . . . . . 1-3GUIDE Toolset . . . . . . . . . . . . . .
1 Getting Started with GUIDE1-223. Add the ItemsSelect File and click the New Menu Item tool. Each time you click New Menu Item, the editor adds a new
Getting Started Example1-235. Activate the GUIAfter creating the menus with the Menu Editor, you can activate the GUI from the Layout Editor. This cau
1 Getting Started with GUIDE1-24Example – Programming the Menu CallbacksAfter adding the File menu to the layout (you cannot see the menu bar in the L
Getting Started Example1-25elseset(handles.print_submenu,'Enable','on')endThe Print Item CallbackThe callback for the Print menu i
1 Getting Started with GUIDE1-26User Interface ControlsThe Layout Editor component palette contains the user interface controls that you can use in yo
User Interface Controls1-27Toggle Buttons Toggle buttons generate an action and indicate a binary state (e.g., on or off). When you click on a toggle
1 Getting Started with GUIDE1-28selected state at any given time). To activate a radio button, click the mouse button on the object. The display indic
User Interface Controls1-29Checkboxes Check boxes generate an action when clicked and indicate their state as checked or not checked. Check boxes are
1 Getting Started with GUIDE1-30You can use the following code in the edit text callback. It gets the value of the String property and converts it to
User Interface Controls1-31For example, these settings create a horizontal slider.Current Value, Range, and Step SizeThere are four properties that co
ii2MATLAB GUIsIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2Creating GUIs with GUIDE . . . . .
1 Getting Started with GUIDE1-32Designing a SliderSuppose you want to create a slider with the following behavior:•Slider range = 5 to 8•Arrow step si
User Interface Controls1-33Use the Bring to Front and Send to Back operations in the Layout menu for this purpose.List Boxes List boxes display a list
1 Getting Started with GUIDE1-34scrollbar). This means the callback is executed after the first click of a double-click on a single item or when the u
User Interface Controls1-35When not open, a popup menu displays the current choice, which is determined by the index contained in the Value property.
1 Getting Started with GUIDE1-36•on – The control is operational•off – The control is disabled and its label (set by the string property) is grayed ou
User Interface Controls1-37makes the axes whose Tag property is axes1 the current axes, and therefore the target for plotting commands. You can switch
1 Getting Started with GUIDE1-38
2MATLAB GUIsIntroduction . . . . . . . . . . . . . . . . . . . . 2-2Creating GUIs with GUIDE . . . .
2 MATLAB GUIs2-2IntroductionA graphical user interface (GUI) is a user interface built with graphical objects, such as buttons, text fields, sliders,
Creating GUIs with GUIDE2-3Creating GUIs with GUIDEMATLAB implements GUIs as figure windows containing various styles of uicontrol objects. You must p
iii3GUIDE Layout ToolsGUI Layout Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2Laying Out GUIs – The Layout Edi
2 MATLAB GUIs2-4Features of the GUIDE-Generated Application M-FileGUIDE simplifies the creation of GUI applications by automatically generating an M-f
Creating GUIs with GUIDE2-5You can elect to have GUIDE generate only the FIG-file and write the application M-file yourself. Keep in mind that there a
2 MATLAB GUIs2-6Editing Version 5 GUIs with Version 6 GUIDEIn MATLAB Version 5, GUIDE saved GUI layouts as MAT-file/M-file pairs. In MATLAB Version 6,
Editing Version 5 GUIs with Version 6 GUIDE2-7application M-file generated by Version 6 GUIDE can provide a model of how to restructure your code.Note
2 MATLAB GUIs2-8Selecting GUIDE Application OptionsIssuing the guide command displays an empty Layout Editor with an untitled figure. Before adding co
Selecting GUIDE Application Options2-9•Generate .fig file and .m file•Generate callback function prototypes•Application allows only one instance to ru
2 MATLAB GUIs2-10Resize BehaviorYou can control whether users can resize the figure window containing your GUI and how MATLAB handles resizing. GUIDE
Resize Behavior2-11This approach works well with simple GUI tools and dialog boxes that apply settings without closing. Users may want to resize these
2 MATLAB GUIs2-12Command-Line AccessibilityWhen MATLAB creates a graph, the figure and axes are included in the list of children of their respective p
Command-Line Accessibility2-13HandleVisibility – CallbackSetting HandleVisibility to callback causes handles to be visible from within callback routin
ivExecution Paths in the Application M-File . . . . . . . . . . . . . . . . 4-4Initializing the GUI . . . . . . . . . . . . . . . . . . . . . . .
2 MATLAB GUIs2-14Electing to Generate Only the FIG-FileSelect Generate .fig file only in the GUIDE Application Options dialog if you do not want GUIDE
The Generated M-File2-15The Generated M-FileSelect Generate .fig file and .m file in the GUIDE Application Options dialog if you want GUIDE to create
2 MATLAB GUIs2-16The arguments are listed in the following table.For example, if you create a layout having a push button whose Tag property is set to
The Generated M-File2-17See Callback Function Syntax for more information on callback function arguments and Renaming Application Files and Tags for m
2 MATLAB GUIs2-18Defining Output Arguments – varargoutGUIDE defines callbacks to return a variable number of arguments using varargout. See Passing Va
The Generated M-File2-19If you select Use system color scheme for background (the default), GUIDE changes the figure background color to match the col
2 MATLAB GUIs2-20Waiting for User InputThe GUIDE application option, Function does not return until application window dismissedgenerates an applicati
Renaming Application Files and Tags2-21Renaming Application Files and TagsIt is often desirable to use descriptive names for component Tag properties
2 MATLAB GUIs2-22If you change the Tag after GUIDE generates the callback subfunction, GUIDE does not generate a new subfunction. However, since the h
Renaming Application Files and Tags2-23When you save or activate the figure, GUIDE changes <automatic> tountitled('pushbutton6_Callback&apo
vPlot Push Button Callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7Launching a Dialog to Confirm an Operation . . . . . . . . .
2 MATLAB GUIs2-24GUIDE generates similar strings for the other callback properties. Changing the Name of the M-File and FIG-FileGUIDE gives the GUI FI
3GUIDE Layout ToolsGUI Layout Tools . . . . . . . . . . . . . . . . . . 3-2Laying Out GUIs – The Layout Editor
3 GUIDE Layout Tools3-2GUI Layout ToolsMATLAB includes a set of layout tools that simplify the process of creating graphical user interfaces (GUIs). T
GUI Layout Tools3-3Component PaletteAlignment ToolMenu EditorProperty InspectorFigure ActivatorObject BrowserLayout AreaFigure Resize TabUndoRedo
3 GUIDE Layout Tools3-4Laying Out GUIs – The Layout EditorThe Layout Editor enables you to select GUI components from a palette and arrange them in a
Laying Out GUIs – The Layout Editor3-5Activating the FigureYou can generate a functioning GUI by activating the figure you have designed with the Layo
3 GUIDE Layout Tools3-6Saving the LayoutOnce you have created the GUI layout, you can save it as a FIG-file (a binary file that saves the contents of
Laying Out GUIs – The Layout Editor3-7Layout Editor Context MenusWhen working in the Layout Editor, you can select an object with the left mouse butto
3 GUIDE Layout Tools3-8GUI Component Context MenusThe following picture shows the context menu associated with uicontrol objects. All the properties t
Laying Out GUIs – The Layout Editor3-9
vi ContentsAn Address Book Reader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-40Techniques Used in This Example . . . . . . . . .
3 GUIDE Layout Tools3-10Aligning Components in the Layout EditorYou can select and drag any component or group of components within the layout area. I
Aligning Components in the Layout Editor3-11•Align – align all selected components to a single reference line.•Distribute – space all selected compone
3 GUIDE Layout Tools3-12All of the align options (vertical top, center, bottom and horizontal left, center, right) place the selected components with
Aligning Components in the Layout Editor3-13Use the Grid and Rulers dialog (accessed by selecting Grid and Rulers from the Layout menu) to:•Control vi
3 GUIDE Layout Tools3-14Front to Back PositioningThe Layout Editor provides four operations that enable you to control the front to back positioning o
Aligning Components in the Layout Editor3-15Access these operations from the Layout menu.
3 GUIDE Layout Tools3-16Setting Component Properties – The Property InspectorThe Property Inspector enables you to set the properties of the component
Setting Component Properties – The Property Inspector3-17•Right-clicking on a component and selecting Inspect Properties from the context menu.
3 GUIDE Layout Tools3-18Viewing the Object Hierarchy – The Object BrowserThe Object Browser displays a hierarchical list of the objects in the figure.
Creating Menus – The Menu Editor3-19Creating Menus – The Menu EditorMATLAB enables you to create two kinds of menus:•Menubar objects – menus displayed
1Getting Started with GUIDEGUIDE – GUI Development Environment . . . . . . . 1-3GUIDE Toolset . . . . . . . . . .
3 GUIDE Layout Tools3-20Creating a MenuThe first step is to use the New Menu tool to create a menu.Specifying Menu PropertiesWhen you click on the men
Creating Menus – The Menu Editor3-21Adding Items to the MenuUse the New Menu Item tool to define the menu items that are displayed under the top-level
3 GUIDE Layout Tools3-22Create additional levels in the same way. For example, the following picture show an Edit menu having a Copy submenu, which it
Creating Menus – The Menu Editor3-23When you activate the figure, the menus appear in the menubar.
3 GUIDE Layout Tools3-24Menu CallbacksBy default, the Callback text field in the Menu Editor is set to the string <automatic>. This causes GUIDE
Creating Menus – The Menu Editor3-25For example, using the Select All menu item from the previous example gives the following callback string:MyGui(&a
3 GUIDE Layout Tools3-26Creating the Parent MenuAll items in a context menu are children of a menu that is not displayed on the figure menubar. To def
Creating Menus – The Menu Editor3-27When you select the menu item, the Menu Editor displays text fields for you to enter the menu Label and Tag proper
3 GUIDE Layout Tools3-28Add a callback routine subfunction to the application M-file for each item in the context menu. This callback executes when us
Saving the GUI3-29Saving the GUIThe FIG-file that you create with the Layout Editor enables MATLAB to reconstruct your GUI when it is deployed. Genera
Komentarze do niniejszej Instrukcji