MATLAB®Creating Graphical User InterfacesR2012a
Adding Callback Templates to an Existing GUI CodeFile... 8-9About GUIDE-Generated Callbacks...
5 GUIDE Preferences and OptionsGUIDE PreferencesIn this section...“Set P refe rences” on page 5-2“Confirmation Preferences” on page 5-2“Backward Compa
GUIDE PreferencesIn the Preferences dialog box, click General > Confirmation Dialogs toaccess the GUID E confirm ation preferences. Look for the wo
5 GUIDE Preferences and OptionsPrompt to Save on ExportWhen you select Export from the Layout Editor File menu, a dialog boxinforms you of the impendi
GUIDE PreferencesTo make a FIG-file backward compatible, selectFile>Preferences>General>MAT-Files,andthenselectMATLABVersion 5 or later (save
5 GUIDE Preferences and OptionsAll Other PreferencesGUIDE p rovides other preferences, for the Layout Editor interface and forinserting code comments.
GUIDE Preferences• “Add Comments for Newly Generated Callback Functions” on page 5-8Show Names in Component PaletteDisplays both icons and names in th
5 GUIDE Preferences and OptionsAdd Comments for Newly Generated Callback FunctionsCallbacks are blocks of code that execute in response to actions by
GUI OptionsGUI OptionsIn this section...“The GUI O ptions Dialog Box” on page 5-9“Resize Be havior” on page 5-10“Command-Line Accessibility” on page 5
5 GUIDE Preferences and OptionsThe following sectio ns describe the options in this dialog bo x:Resize BehaviorYou cancontrol w hether users can resiz
GUI Optionssee the GUIDE examples “Panel” on page 8-38 and “An Address B ook Reader(GUIDE)” on page 10-81. Also see the example “Using Panel Container
Data Management Mechanism Summary ... 9-2Nested Functions... 9-4UserData Property...
5 GUIDE Preferences and OptionsOption DescriptionCallback (GUI becomes CurrentFigure within Callbacks)The GUI can be accessed onlyfrom within a GUI ca
GUI OptionsGUIDE also adds a callback whenever you edit a callback routine from theLayout Editor’s right-click context menu and when you add menus to
5 GUIDE Preferences and OptionsUse System Color Scheme for BackgroundThe default color u sed for GUI components is system dependent. This optionenable
GUI Optionslimited editing capability and may be useful for GUIs generated in MATLABVersions 5.3 and earlier. See theguide function for more informati
5 GUIDE Preferences and Optionsarguments to that function. For example, setting the Callbac k property ofapushbuttontosqrt(2) causes the result of the
6Lay 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• “Ad
6 Lay Out a GUIDE GUIDesign a GUIBefore creating the actual GUI, it is important to decide what it is you wantyour GUI to do and how you want it to wo
Design a G UI• AskTog — Essays on good design and a list of FirstPrinciples for good user interface design. The author, BruceTognazzini, is a well-res
6 Lay Out a GUIDE GUIStar t GUIDEThere are many ways to start GUIDE. You can s tart GUIDE from the:• Command line by typingguide• Start menu by select
Start GUIDE• Open Existing GUI —EnablesyoutoopenanexistingGUIinGUIDE.You can choose a GUI from your current folder or browse other directories.6-5
About the List Box Directory Example ... 10-54View and Run the List Box Directory GUI... 10-55Implement the List Box Directory
6 Lay Out a GUIDE GUISelect a GUI TemplateIn this section...“Access the Templates” on page 6-6“Template Descriptions” on page 6-7Access the TemplatesG
Select a GUI TemplateTo 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 s
6 Lay Out a GUIDE GUIBlank GUIThe blank GUI template displayed in the Layout Editor is shown in thefollowing figure.Select the blank GUI if the other
Select a GUI TemplateGUI with UicontrolsThe following figure shows the template for a GUI with user interface controls(uicontrols) displayed in the La
6 Lay Out a GUIDE GUIWhen you run the GUI by clicking the Run button ,theGUIappearsasshown in the following figure.When a user enters values f or the
Select a GUI TemplateWhen you run the GUI by clicking the Run button on the toolbar, theGUI d is plays a plot of five lines, each o f which is generat
6 Lay Out a GUIDE GUIYou can select other p lo ts in the pop-up menu. Clicking the Up date buttondisplays the currently selected plot on the axes .The
Select a GUI TemplateModal Question DialogThe m odal question dialog template displayed in the Layout Editor is shownin the following figure.Running t
6 Lay Out a GUIDE GUIThe GUI returns the text string Yes or No, depending on which button youclick.Select this template if you want your GUI to return
Set the GUI SizeSet the GUI SizeSet the size of the GUI by resizing the grid area in the Layout Editor.Click the lower-right corner and drag it until
Run the Close-Confirmation GUI ... 10-102How the Close-Confirmation GUIs Work... 10-103Time Data Updates from a GUI (GUID
6 Lay Out a GUIDE GUINote Many of the following steps show you how to use the P roperty Inspectorto set properties of a GUI and its components. If you
Set the GUI Size4 Type the x and y coordinates of the point where you w ant the lower-leftcorner of the GUI to appear, and its width and height.5 Rese
6 Lay Out a GUIDE GUIMaximize the Layout AreaYou can make maximum use of space within the Layout Editor by hidingthe G UIDE toolbar, status bar, or bo
Add Components to the GUIAdd Components to the GUIIn this section...“Available Com ponents” on page 6-20“A Working GUI with Many Components” on page 6
6 Lay Out a GUIDE GUIAvailable ComponentsThe component palette at th e left side of the Layout Editor contains thecomponents thatyou can add to your G
Add Components to the GUIComponent Icon DescriptionPush Button Push buttons generate an action w h en clicked.For example, an OK button might apply se
6 Lay Out a GUIDE GUIComponent Icon DescriptionPop-Up MenuPop-up menus open to display a list of choiceswhen users click the arrow.List BoxList boxes
Add Components to the GUIComponent Icon DescriptionButton GroupButton groups are like panels but are used tomanage exclusive selection behavior for ra
6 Lay Out a GUIDE GUI• Clickheretodisplaythecontrolsuite GUI in the GUIDE Layout Editor.• Clickheretodisplaythecontrolsuite GUIcodefileintheMATLABEdit
Add Components to the GUIThe GUI contains 15 controls organized within seven panels. The ActionPanel contains a static text component that changes to
Set Tab Order in a Programmatic GUI ... 11-70How Tabbing Works... 11-70Default Tab Order...
6 Lay Out a GUIDE GUIRun the controlsuite GUIWhen you click the Run Figure button in the Layout Editor, the GUIopens, initializes, and displays itself
Add Components to the GUIThe code that generates the message is part of the pushbutton1_Ca llback,shown below :function pushbu tton 1_Callback(hObject
6 Lay Out a GUIDE GUI% hObject handle to togglebutton1 (see GCBO)% eventdata re serv ed - to be defi ned in a future ver sion of MATLAB% handles struc
Add Components to the GUIThe popup’s callback controls its behavior. GUIDE generates this much ofthe callback.function popupm enu1 _Callback(hObject,
6 Lay Out a GUIDE GUIretrieve the nam e of the colormap That name, selectedTex t,iscomposedinto a message and placed in thetextStatus static text fiel
Add Components to the GUIFor another example describing how to couple uitables with graphics, see“GUI to Interactively Explore D ata in a T able (GUID
6 Lay Out a GUIDE GUIIf You Are Adding...Then...Panels or butto n groupsSee “Add a Component to a Panelor Button Group” on page 6-34.MenusSee “Create
Add Components to the GUIThis is an example of a GUI in the Layout Editor. Components in the LayoutEditor are not active.Use Coordinates to Place Comp
6 Lay Out a GUIDE GUIdistances are relative to the parent figure, panel, or button group. Allvalues are giv en in pix e ls. Rulers also display pix el
Add Components to the GUIGUIDE highlights the potential parent as shown in the following figure. Thehighlight indicates that if you drop the component
Program ActiveX Controls ... 12-34Program M enu Items... 12-34Program Toolbar Tools...
6 Lay Out a GUIDE GUIInclude Existing Components in Panels and Button Groups. Whenyou add a new component or drag an existing component to a panel orb
Add Components to the GUIThe panel highlights when you move a control, indicating it now containsthe control. The Object Browser updates to confirm th
6 Lay Out a GUIDE GUI3 In the Property Inspector, select Tag and then replace the value with thestringyouwanttouseastheidentifier. Inthefollowingfigur
Add Components to the GUI• “Static Text” on page 6-48• “Pop-Up Menu” on page 6-50• “ListBox”onpage6-52• “Toggle Button” on page 6-54Note See “Availabl
6 Lay Out a GUIDE GUIPropertyValueDescriptionStringString. Can also be acell array or characterarray of strings.Component label. Forlist boxes and pop
Add Components to the GUITo display the & character in a label, use two & characters in the string.The wordsremove, default,andfactory (case s
6 Lay Out a GUIDE GUINote Create your own icon with the icon editor described in “Icon Editor”on page 15-63. Seeind2rgb for information on converting
Add Components to the GUIclicking the trough m oves the slider thumb. Setting it to 1 or higher causesthethumbtomovetoMax or Min w hen the trough is c
6 Lay Out a GUIDE GUI• Specify the radio button label by setting the String property to the desiredlabel, in this case,Indent neste d functions.To dis
Add Components to the GUI• Ifyouwanttosetthepositionorsizeofthecomponenttoanexactvalue,then modify itsPosition property. See “Locate and Move Componen
GUI with Axes, Menu, and Toolbar ... 15-4About the Axes, M en u, and Toolbar Example... 15-4View and Run the AxesMenuT oolbar C
6 Lay Out a GUIDE GUITo display the & character in a label, use two & characters in the string.The wordsremove, default,andfactory (case sensi
Add Components to the GUI• Specify the text to be displayed when the edit text component is createdby setting theString property to the d esired strin
6 Lay Out a GUIDE GUIIf Max-Min is less than or equal to 1, the edit text component admits only asingle line of input. If you specify a component widt
Add Components to the GUI• Specify the text that appears in the component by setting the componentString property to the desired text, in this caseSel
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 MenuTo
Add Components to the GUITo display the & character in a menu i tem, use two & characters in thestring. The wordsremove, default,andfactory (c
6 Lay Out a GUIDE GUI• If you w ant to set the position and size of the component to exact values,then modify itsPosition property. See “Locate and Mo
Add Components to the GUITo display the & character in a label, use two & characters in the string.The wordsremove, default,andfactory (case s
6 Lay Out a GUIDE GUI- To select more than one item when the component is created, set Valueto a vector of indices of the s elected items. Value = [1,
Add Components to the GUI• Specify the toggle button label b y setting its String property to the desiredlabel, in this case,Left/Right Ti le.To displ
ExamplesASimple Examples (GUIDE) ... A-2Simple Examples (Programmatic)... A-3Application Examples (GUIDE)...
6 Lay Out a GUIDE GUIsoftware sets Value to Max,andtoMin when the user deselects it. Thefollowing figure shows the toggle button in the depressed posi
Add Components to the GUI1 Use the Property Inspector to modify the appropriate properties. Open theProperty Inspector by selecting Prop erty Insp ect
6 Lay Out a GUIDE GUIProperty Values DescriptionTitlePosition lefttop, centertop ,righttop, leftbott om,centerbottom,rightbottom.Defaultislefttop.Loca
Add Components to the GUI• Specify the panel title by setting the Title property to the desired string,in this caseMy Panel.To display the & chara
6 Lay Out a GUIDE GUI• Ifyouwanttosetthepositionorsizeofthepaneltoanexactvalue,thenmodify itsPosition property. See “Locate and Move Components” on pa
Add Components to the GUITo display the & character in the title, use two & characters in the string.The words remove, default, and factory (c
6 Lay Out a GUIDE GUINote For more information and additional tips and techniques, see“Add a Component to a Panel or Button Group” on page 6-34 and th
Add Components to the GUIProperty Values DescriptionNextPlot add, replace,replacechildren.Default isreplaceSpecifies whetherplotting adds graphics,rep
6 Lay Out a GUIDE GUI• Allow for tick marks to be placed outside the box that appears in the LayoutEditor. The axes above looks l ike this in the layo
Add Components to the GUI• Use thetitle, xlabel, ylabel, zlabel,andtext functions in the GU Icode file to label an axes component. For example,xlh = (
xviii Contents
6 Lay Out a GUIDE GUI• If you customize axes properties, some of them ( or example, callbacks, fontcharacteristics, and axis limits and ticks) may get
Add Components to the GUIGroupPropertyValuesDescriptionColumnName1-by-n cell arrayof strings |{’numbered’} |emptymatrix([])The h eader labelof the col
6 Lay Out a GUIDE GUIDrag the table icon on to the Layout Editor and right click in the table. SelectTable Property E ditor from its pop-up context me
Add Components to the GUIUse theTable Property Editor. When you open it this way, the TableProperty Editor displays the Column pane. You can also open
6 Lay Out a GUIDE GUIButton PurposeAccelerator KeysWindows MacintoshInsertInserts a new column or rowdefinition entry below the currentoneInsert Inser
Add Components to the GUISelect Show names entered below as the column headers and s et theColumnName by entering Rate, Amount, Available, and F ixed/
6 Lay Out a GUIDE GUIFor the Rate column, select Numeric. For the Amount Column selectCustom and in the C ustom Format Editor, choose Bank.6-72
Add Components to the GUILeave the Available column at the default value. This allows MATLAB tochose based on the value of theData property of the tab
6 Lay Out a GUIDE GUINote The In order for a user to select items from a choice list, theColumnEditable property of the column the list occupies must
Add Components to the GUISet Data Properties. Specify the value of the Data you want in the table.You need createData in the MATLAB command window bef
Introduction to Creating GUIsChapter 1, About GUIs inMATLAB Software (p. 1-1)Explains what a GUI is, howaGUIworks,andhowtogetstarted creating a GUI.Ch
6 Lay Out a GUIDE GUISet Color Properties. Specify the Bac kgroundColor and RowStriping foryour table in the Color tab.6-76
Add Components to the GUIYou can change other uitable properties to the table via the PropertyInspector.Add ActiveX ControlsWhen you drag a n A ctiveX
6 Lay Out a GUIDE GUINote If MATLAB software is not installed locally on your computer — forexample, if you are running the software over a network —
Add Components to the GUI2 Click Create. The control appears as a small box in the Layout Editor.3 Resize the control to approximately the size of the
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
Add Components to the GUINote You can select multiple components onlyiftheyhavethesameparent.To determ ine the child objects of a figure, panel, or bu
6 Lay Out a GUIDE GUIthe selected components. Look for the highlight as described in “Add aComponent to a Panel or Button Group” on page 6-34.Front-to
Add Components to the GUI• Send to Back — Move the selected object(s) behind n onse lecte d objects(available from the right-click context menu, the L
6 Lay Out a GUIDE GUIIf you drag or resize the component, the readout updates accordingly. Thereadout to the left of the component position readout di
Add Components to the GUIUse Arrow Keys to Move ComponentsSelect one or more components that you w ant to move, then press and holdthe arrow keys unti
How to Contact MathWorkswww.mathworks.comWebcomp.soft-sys.matlab Newsgroupwww.mathworks.com/contact_TS.html Technical [email protected] Pro
6 Lay Out a GUIDE GUI2 Click the + sign next to Position. The Property Inspector displays theelements of thePosition property.3 If you have selected•
Add Components to the GUIDrag a Corner of the ComponentSelect the component you want to resize. Click one of the corner handles anddrag it until the c
6 Lay Out a GUIDE GUI2 Click the + sign next to Position. The Property Inspector displays theelements of thePosition property.3 Type the width and hei
Align ComponentsAlign ComponentsIn this section...“Align O bjects Tool” on page 6 -89“Property Inspector” on page 6-92“Grid a nd Rulers ” on page 6-96
6 Lay Out a GUIDE GUITheAlignObjectstoolprovidestwotypesofalignmentoperations:• Align — Align all selected components to a single reference line.• Dis
Align ComponentsAlign OptionsThere are both vertical and horizontal align options. E ach option alignsselected components to a reference line, which i
6 Lay Out a GUIDE GUIBoth modes enable you to specify how the spacing is measured, as indicatedby the button labels on the alignment tool. These optio
Align ComponentsScroll down to see additional properties. C lick any property value or icon totheleftofonetosetitsvalue,eitherdirectlyinthatfieldorvia
6 Lay Out a GUIDE GUIThe Property Inspector provides context-sensitive help for individualproperties. Right-clicking a property nam e or value opens a
Align Components2 Select Property Inspector from the View menu or click the PropertyInspector button.3 In the Property Inspector, scroll to the Units
1About GUIs in MATLABSoftware• “What Is a G U I?” on page 1-2• “How Does a GUI W ork?” on page 1-4• “Where Do I Start?” on page 1-6• “Ways to Build MA
6 Lay Out a GUIDE GUIGrid and RulersThe layout area displays a grid a nd rulers to facilitate component layout.Grid lines are spaced at 50-pixel inter
Align ComponentsCreating Guide LinesTo create a guide line, click the top or left ruler and drag the line into thelayout area.6-97
6 Lay Out a GUIDE GUISet Tab OrderA GUI’s tab order is the order in which com ponents of the GUI acquire focuswhen a user presses the Tab key on the k
Set Tab OrderThe 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,
6 Lay Out a GUIDE GUITo examine and change the tab order of the panel components, click the panelbackground to select it, then select Tab Order Editor
Create Menus in a GUIDE GUICreate Menus in a GUIDE GUIIn this section...“Menus for the Menu Bar” on page 6-102“Context Menus” on page 6-114You can use
6 Lay Out a GUIDE GUINoteSee “Menu Item” on page 8-59 and “Updating a Menu Item C heck” onpage8-61 for info rm ation abou t progra m m i n g and basic
Create Menus in a GUIDE GUI• “CreateaMenu”onpage6-106• “Add Items to a Menu” on page 6-109• “Additional Drop-Down M enus” on page 6-111• “Cascading Me
6 Lay Out a GUIDE GUIThe WindowStyle figure property also affects docking behavior. The default is'normal', but if you change it to 'do
Create Menus in a GUIDE GUIIn either case, you can enable u sers of your GUI to dock and undock it usingits docking arrow by setting the figure’sDockC
1 About GUIs in MATLAB®SoftwareWhat Is a GUI?A graphical user interface (G UI) is a graphical display in one or morewindows containing controls, calle
6 Lay Out a GUIDE GUICreate a Menu1 Start a new menu b y clicking the New Menu button in the toolbar. A menutitle,Untitled 1, appears in the left pane
Create Menus in a GUIDE GUI2 Click the menu title to display a selection of menu properties in the rightpane.3 Fill in the Label and Tag fields for th
6 Lay Out a GUIDE GUIremove, default,andfactor y (case sensitive) are reserved. To use oneof these as labels, prepend a backslash (\) to the string. F
Create Menus in a GUIDE GUIAdd Items to a MenuUse the New Menu Item tool to create menu items that are displayed inthe drop-down menu.1 Add an Open me
6 Lay Out a GUIDE GUI2 Fill in the Label and Tag fields for the new menu item . For example, setLabel toOpen and set Tag to menu_file_open. Click outs
Create Menus in a GUIDE GUIsome accelerators may be used for other purposes on your system and thatother actions may result.• Di splay a sepa rator ab
6 Lay Out a GUIDE GUICascading MenusTocreateacascadingmenu,selectthemenuitemthatwillbethetitleforthecascading menu, then click the New Menu Item butto
Create Menus in a GUIDE GUINote See “Menu Item” on page 8-59 for information about programmingmenu items.The following Menu Editor illustration shows
6 Lay Out a GUIDE GUIContext MenusA co ntext menu is displayed w he n a user right-clicks the object for which themenuisdefined. TheMenuEditorenablesy
Create Menus in a GUIDE GUI1 Select the Menu Editor’s Context Menus tab and select the New ContextMenu button from the toolbar.6-115
What Is a GUI?• Three buttons that provide different kinds of plots: surface, mesh, andcontourWhen you click a push button, the axes component display
6 Lay Out a GUIDE GUI2 Select the menu and specify the Tag field to identify the context m enu(axes_context_menu in this example).Add Items to the Con
Create Menus in a GUIDE GUI6-117
6 Lay Out a GUIDE GUI2 Fill in the Label and Tag fields for the new menu item . For example, setLabel toBlue background color and set Tag to blue_back
Create Menus in a GUIDE GUIopened. If you clear this option, the menu item appears dimmed when themenu is first opened, and the user cannot select it.
6 Lay Out a GUIDE GUIThe View button displays the callback, if there is one, in an editor. If youhave not yet saved the GUI, GUIDE prompts you to save
Create Menus in a GUIDE GUINote See “Menu Item” on page 8-59 and “Updating a Menu Item C heck” onpage 8-61 for programming information and basic examp
6 Lay Out a GUIDE GUICreate ToolbarsIn this section...“Create Toolbars with GUIDE” on page 6-122“Editing Tool Icons” on page 6-131Create Toolbars with
Create ToolbarsThe Toolbar Editor gives you interactive access to all the features of theuitoolbar, uipushtoo l,andu itoggletool functions. It only op
6 Lay Out a GUIDE GUINote You do not need to use the Toolbar Editor if you simply want your GUIto have a standard figure toolbar. You can do this by s
Create ToolbarsTo add a tool, drag an icon from the Tool Palette into the Toolbar Layout(which initially contains the text prompt shown above), and e
1 About GUIs in MATLAB®SoftwareHow Does a GUI Work?In the GUI described in “W hat Is a GUI?” on page 1-2, the user selects a dataset from the pop-up m
6 Lay Out a GUIDE GUIWhen you f irst create a GUI, no toolbar exists on it. When you open theToolbar E ditor and place the first tool, a toolbar is cr
Create ToolbarsPredefined and Custom ToolsThe Toolbar E ditor 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 n o b ehaviorsPredefined Tools. T
Create ToolbarsMove ToolsYou 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
6 Lay Out a GUIDE GUISee “Working with Callbacks in G UIDE” on page 8-2 for details onprogramming the tool callbacks. You can also access these and ot
Create ToolbarsRemove a ToolbarYou can remove a toolbar completely— destroying it— from the Toolbar Editor,leaving your GUI without a toolbar (other t
6 Lay Out a GUIDE GUINote There are examples that show how to create your own icon e ditor. Seethe example in “Icon Editor” on page 15-63 and the disc
Create ToolbarsUse the I con EditorThe Icon Editor G UI includes the following components:• Icon file name —Theiconimagefiletobeloadedforediting• Impo
6 Lay Out a GUIDE GUI• Ho ld down the left mouse button an d drag the mous e over the grid totransfer the selected color to the squares that you touch
Create Toolbars6-135
How Does a GUI Work?running at those times. This distinguishes event-driven programming fromother types of control flow, for example, processing seque
6 Lay Out a GUIDE GUIView the Object HierarchyThe O bject Browser displays a hierarchical list of the objects in the figure,including both components
Designing for Cross-Platform CompatibilityDesigning for Cross-Platform CompatibilityIn this section...“Default System Font” on page 6-137“Standard Bac
6 Lay Out a GUIDE GUISpecify a Fixed-Width FontIf you w ant to use a fixed-width font for a user interface control, set itsFontName property to the st
Designing for Cross-Platform CompatibilityThe following figures illustrate the results with and without system colormatching.Cross-Platform Compatible
6 Lay Out a GUIDE GUIUnits and Resize BehaviorIf you set your GUI’s resize behavior from the GUI Options dialog box,GUIDE automatically sets the units
7Save and Run a GUIDEGUI• “NameaGUIandItsFiles”onpage7-2• “Save a G U IDE GUI” on page 7-4• “Run a GUIDE GUI” on page 7-10
7 Save and Run a GUIDE GUINameaGUIandItsFilesIn this section...“The GUI Files” on page 7-2“File and GUI Names” on page 7-3“Rename GUIs and GUI Files”
NameaGUIandItsFilesFor more information about these files, see “Files Generated by GUIDE”on page 8-7.File and GUI NamesThecodefileandtheFIG-filethatde
7 Save and Run a GUIDE GUISave a GUIDE GUIIn this section...“Ways to Save a GUI” on page 7-4“Save a New GUI” on page 7-5“SaveanExistingGUI”onpage7-8“E
Save a GUIDE GUIIn 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,
1 About GUIs in MATLAB®SoftwareWhere Do I Start?Before starting to construct a GUI you have to design it. At a minimum,youhavetodecide:• Who the GUI u
7 Save and Run a GUIDE GUINote If you select Save as from the File menu or click the Save buttonon the toolbar, GUID E saves the GUI without activatin
Save a GUIDE GUI4 If you choo se a n e xisting filen ame, GUIDE di splays a dialog bo x th at asksyou i f you want to replace the existing FIG-file. C
7 Save and Run a GUIDE GUI6 If you chose to activate the GUI by selecting Run fro m the Tools menuor by clicking the Run buttonon the toolbar, and if
Save a GUIDE GUIIf you select Save from the File menu or click the Save button on thetoolbar, GUIDE saves the GUI without activating it.ExportaGUIDEGU
7 Save and Run a GUIDE GUIRun a GUIDE GUIIn this section...“Execute GUI Code” on page 7-10“From the GUIDE Layout Editor” on page 7-10“From the Command
Run a GUIDE GUIIn either case, if the GUI has changed or has never been saved, GUID E savesthe GUI files before activating it and opens the GUI code f
7 Save and Run a GUIDE GUIThe GUI files must reside on the MATLAB path or in the current MATLABfolder where the GUI is run.If a GUI accepts arguments
Run a GUIDE GUIfor val = 1:3set(handles.plot_popup,'Value',val)simple_gui('plot_popup_Callback',...handles.plot_popup,[],handles)%
7 Save and Run a GUIDE GUI7-14
8Programming a GUIDEGUI• “Working with Callbacks in GUIDE” on page 8-2• “Files Generated by GUIDE” on page 8-7• “Default Callback Properties in GUIDE”
Where Do I Start?UnderstandRequirements Purpose Use cases Interactivity FunctionalitySpecify GUI(s) Inputs Controls Displays Behavior Outputs
8 Programming a GUIDE GUIWorking with Callbacks in GUIDEIn this section...“Programming GUIs Created Using GUIDE” on page 8-2“What Is a Callback?” on p
Working with Callbacks in GUIDEof that component. For example, a push button has five callback properties:ButtonDownFcn, Callback, CreateFcn, DeleteFc
8 Programming a GUIDE GUICallback Property Triggering Event ComponentsCreateFcnInitializes the componentwhen a function createsit. It executes after t
Working with Callbacks in GUIDECallback Property Triggering Event ComponentsSelectionChangeFcnExecutes when a GUI userselects a different radiobutton
8 Programming a GUIDE GUINote User interface controls include push buttons, sliders, radio buttons,check boxes, editable text boxes, st atic text boxe
Files Generated by GUIDEFiles Generated by GUIDEIn this section...“Code Files and FIG-Files” on page 8-7“GUI Code File Structure” on page 8-8“Adding C
8 Programming a GUIDE GUIFor more information, see “Name a GUI and Its Files” on page 7-2,“Save aGUIDE GUI” on page 7-4, and“Re name G UIs an d GU I F
Files Generated by GUIDEAdding CallbackTemplates to an Existing GUI CodeFileWhen you save theGUI, GUIDE automatically adds templates for somecallbacks
8 Programming a GUIDE GUIGUIDE names callbacks based on the callback type and the componentTag property. For example, togglebutton1_Callb ack is such
Default Callback Properties in GUIDEDefault Callback Properties in GUIDEIn this section...“Setting Callback Properties Automatically” on page 8-11“Del
1 About GUIs in MATLAB®SoftwareWays to Build MATLAB GUIsA M ATLAB GUI is a figure window to which you add user-operated controls.You can select, size,
8 Programming a GUIDE GUIThe following figure shows properties of a push button in the GUID EProperty Inspector prior to saving the GUI. GUIDE set the
Default Callback Properties in GUIDEWhen you save the GUI, GUIDE constructs the name of the callback byappending an underscore (_) and the name o f th
8 Programming a GUIDE GUIWhen you save th e GUI, GUIDE also o pens the GUI code file in y ou r e di tor.The file then contains a template for theCallb
Customizing Callbacks in GUIDECustomizing Callbacks in GUIDEIn this section...“GUIDE Callback Templates” on page 8-15“Callback Names and Signatures in
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
Customizing Callbacks in GUIDEproperty for the push button, and Callback is one of the push button’s callbackproperties. TheTag property uniquely iden
8 Programming a GUIDE GUI@(hObject,eventdata)mygui('pushbutton1_Callback',hObject,eventdata,guidata(hObject))The syntax @(hObject,eventdata)
Customizing Callbacks in GUIDE@(hObject,eventdata)mygui('pushbutton1_Callback',hObject,eventdata,guidata(hObject))Saving a GUI with a push b
8 Programming a GUIDE GUIGUIDE Callback ArgumentsAll callbacks ina GUIDE-generated GUI code file have the following standardinput arguments:•hObject —
Customizing Callbacks in GUIDE• KeyP ress Fcn in uicontrols and figures•KeyReleaseFcn in a figure•SelectionChangeFcn in a uibuttongroup•WindowKeyPress
Ways to Build MATLAB®GUIsType of GUI TechniqueDialog boxMATLAB software provides aselection of standard dialog boxesthat you can create with a singlef
8 Programming a GUIDE GUIthe programmatic uitable example “GUI that Dis plays a nd Graphs TabularData” on page 15-19.handles StructureGUIDE creates a
Customizing Callbacks in GUIDEwarnbeforesave. If possible, change the Tag property before saving the GUIto cause GUIDE to autom atically create callba
8 Programming a GUIDE GUIClick Yes to revert to the GUID E auto-generated callback. click No to keepthe modified callback.Note Remember to change the
Initialize a GUIDE GUIInitialize a GUIDE GUIIn this section...“Opening Function” on page 8-25“Output F unction” on page 8-28Opening FunctionThe openin
8 Programming a GUIDE GUI% Update handles structureguidata(hObject, h andles);% UIWAIT makes mygui wait for user response (see UIRESUME)% uiwait(handl
Initialize a GUIDE GUIGUI template, available from the GUIDE Quick Start dialog box. The addedcode opens the modal dialog w ith a message, specified f
8 Programming a GUIDE GUI...The if block loops through the odd elements of varargi n checking forproperty names or aliases, and thecase blocks assign
Initialize a GUIDE GUIFunction Naming and TemplateGUIDE names the output function b y appending _OutputFcn tothenameofthe G UI. This is an example of
8 Programming a GUIDE GUIAdd Code for Components in CallbacksIn this section...“Push B utton” on page 8-30“Toggle Button” on page 8-31“Radio Button” o
Add Code for Components in C allbacksThis is the push button’s Callback callback. It displays the string Goodbye atthe command line and then closes th
Revision HistoryNovember 2000 Online Only New for MATLAB 6.0 (Release 12)June 2001 Online Only Revised for MATLAB 6.1 (Release 12.1)July 2002 Online O
1 About GUIs in MATLAB®Software1-10
8 Programming a GUIDE GUIbutton_state = get(hObject,'Value');if button_st ate == get(hObject,'Max')% Toggle button is pressed, tak
Add Code for Components in C allbacksselects the radio button with Tag property radiobutton1 and deselects thepreviously selected radio button.Note Yo
8 Programming a GUIDE GUIIf the edit text Max and Min properties are set such that Max - Min > 1,theuser can enter m ultiple lines. For example, se
Add Code for Components in C allbacksAvailable Keyboard AcceleratorsGUI users can use the following keyboard accelerators to modify the contentof an e
8 Programming a GUIDE GUITable CellSelectionCallbackEverytimetheuserselectsatablecell,thetable’sCellSelectionCallbackfires. This happens whether table
Add Code for Components in C allbacksselects the second item in the list box w ith Tag property listbox1.Triggering Callback ExecutionMATLAB software
8 Programming a GUIDE GUIUsing Only the Index of the Selected Menu ItemThis example retrieves only the index of the item selected. It uses a switchsta
Add Code for Components in C allbacksgroups as well as axes and u ser interface controls such as push buttons,sliders, pop-up menus, etc. The position
8 Programming a GUIDE GUI2 Create callbacks for the two push buttons, and place the follow ing line ofcode in each of them.set(gcbf,'Position&apo
Add Code for Components in C allbacksset(buttons(1),'FontSize',newFontSi ze); % Resize the first button% Do not resize the other button for
2How to Create a G UI withGUIDE• “Introduction to GUIDE” on page 2-2• “Abo ut the Simple GUIDE GU I Example” on page 2-9• “Lay Out the Simple GUI in G
8 Programming a GUIDE GUITip You can enable text in controls to resize automatically by setting thecomponent’sfontUnits to normalized, without the nee
Add Code for Components in C allbacksIf a user clicks the other radio button or one of the toggle buttons, it becomesselected and Radio B utton 1 is d
8 Programming a GUIDE GUI• Select SelectionChangeFcn from the View > View C allbacks submenu,or• Right-click and select SelectionChangeFcn from the
Add Code for Components in C allbacksAxesAxes components enable your GUI to display graphics, such as graphs andimages. This topic briefly tells you h
8 Programming a GUIDE GUI1 Add this code to the Plot 1 push button’s Callback callback. The surffunction produces a 3-D shaded surface plot. The peaks
Add Code for Components in C allbacksNote For information about properties that you can set to control manyaspects of axes behavior and appearance, se
8 Programming a GUIDE GUITip When working with multiple axes, it is best not to “raise” the axes y ouwant to plot data into with commands likeaxes(a1)
Add Code for Components in C allbacksFor more information about subplots, see the subplot reference page. Forinformation about adding panels to your G
8 Programming a GUIDE GUINote The following links execute MATLAB commands and are designed towork w ithin the MATLAB Help brow ser. If you are reading
Add Code for Components in C allbacksNote Clicking Create places a copy of the file Mwsamp_activex1 in yourworking folder. If you move your GUI files
2 How to Create a GUI with GUIDEIntroduction to GUIDEIn this section...“What Is GUIDE?” on page 2-2“Opening G U IDE ” on page 2-2“Getting Help in GUID
8 Programming a GUIDE GUIpane. The following figure shows the ActiveX control as it appears in theLayout Editor.If you need help adding the component,
Add Code for Components in C allbacks5 View the ActiveX Properties with the Property Inspector. Select the controlin the Layout Editor, and then selec
8 Programming a GUIDE GUI7 Add the following code to the mswamp control’s active x1_Click callback.This code programs the ActiveX control to change th
Add Code for Components in C allbacksProgramming a User Interface Control to Update an ActiveXControlThis topic continues the previous example by addi
8 Programming a GUIDE GUIViewing the Methods for an ActiveX ControlTo view the available methods for an ActiveX control, you first need to obtainthe h
Add Code for Components in C allbacksAlternatively, you can entermethods(hObject)which displays the available methods in the MATLAB Command Window.For
8 Programming a GUIDE GUICompiling a GUI That Contains an ActiveX ControlIf you use the MATLAB Compiler mcc command to compile a GUI thatcontains an A
Add Code for Components in C allbacksMenu ItemThe G UIDE M enu Editor generates an empty callback subfunction for everymenu item, including menu title
8 Programming a GUIDE GUIMouse Gestures and Menu Callback Behavior. Callback s for leaf me n uitems, such as for to file or to clipboard in the previo
Add Code for Components in C allbacksUpdating a Menu Item CheckA check is useful to indicate the current state of some menu items. If youselected Chec
Introduction to GUIDEWhen you right-click a FIG-file in this way, the figure opens in the GUIDELayout Editor, where you can work on it.2-3
8 Programming a GUIDE GUI8-62
9Managing and SharingApplication 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 Sh aring Application Data in GUIDEWays to Manage Data in a GUIDE GUIIn this section...“Data Management Mechanism Summary” on page 9-2“N
Ways to Manage Data in a GUIDE GUIData-SharingMethodHow it WorksUse for...Pass function handlesor data through oneof the four followingmethods:Exposin
9 Managing and Sh aring Application Data in GUIDE• Nested Functions — Share variables defined at a higher level and callone another when called functi
Ways to Manage Data in a GUIDE GUIUserData PropertyAll GUI components, including menus and the figure itse lf have a UserDataproperty. Y ou can assign
9 Managing and Sh aring Application Data in GUIDEOnly Handle Graphics MATLAB objects use this property. The following tablesummarizes the functions th
Ways to Manage Data in a GUIDE GUIAdding Fields to an Application Data Structure in GUIDEApplication data is usually defined as a structure. This enab
9 Managing and Sh aring Application Data in GUIDE• GUI d ata is a single variable; how ever, when defined as a structure, youcan add and remove fields
Ways to Manage Data in a GUIDE GUIadds the field number_errors to the ha ndle s structure and sets it to 0.2 Use the following com mand to save the da
2 How to Create a GUI with GUIDEAll tools in the tool palette have tool tips. Setting a GUIDE preference letsyou display the palette in GUIDE with too
9 Managing and Sh aring Application Data in GUIDEmeans while it is currently running, its internal state might not need to beinitialized again. One wa
Ways to Manage Data in a GUIDE GUIIf the user types a number between 0 and 1 in the edit text componentand then presses Enter or clicks outside the ed
9 Managing and Sh aring Application Data in GUIDE1 Click here to copy the files to your current folder.2 Type guide slider box_ userdata or click here
Ways to Manage Data in a GUIDE GUIThis section shows you h ow to use GUI data to initialize and maintain anerror counter by storing an error count in
9 Managing and Sh aring Application Data in GUIDEset(hObject,'UserData',data);% Display new total.set(hObject,'String',...['Y
Ways to Manage Data in a GUIDE GUI2 Type guide slide rbox _appdata or click here to open the GUI in GUIDE.3 Type edit sliderbox_appdata orclickheretoo
9 Managing and Sh aring Application Data in GUIDEThe section “Sharing Data with GUI Data” on page 9-17 uses GUI data toinitialize and maintain an erro
Ways to Manage Data in a GUIDE GUIslider_data = getappdata(handles.figure1,'slider');slider_data.number_errors = sli der_data.number_errors+
9 Managing and Sh aring Application Data in GUIDE3 edit sli derb ox_guidata or click here to open the GUI code file in theEditor.You can view the prop
Ways to Manage Data in a GUIDE GUI• When a user types a value into the edit text component, the slider updatesto this value.• If a user enters a value
Introduction to GUIDEThe first three options lead you to topics in the GUIDE documentation thatcan help you get started using GUIDE. The Example GUIs
9 Managing and Sh aring Application Data in GUIDE• The set command sets the String property of the edit text to theupdated value.3 Set the slider valu
Making Multiple GUIs Work TogetherMaking Multiple GUIs Work TogetherIn this section...“Data-Sharing Techniques” on page 9-21“Example — Manipulating a
9 Managing and Sh aring Application Data in GUIDEExample — Manipulating a Modal Dialog Box forUser Input• “View and Run the changeme GUI” on page 9-23
Making Multiple GUIs Work TogetherNote The changeme_dialog GUI is patterned after the MATLAB inpu tdlgfunction, a predefined dialog box that serves th
9 Managing and Sh aring Application Data in GUIDEYou can view the properties of any component by double-clicking it in theLayout Editor to open the Pr
Making Multiple GUIs Work Togetherchangeme_dialog('changeme_main', handles.figure);ThedialogboxusesthehandletoaccessthemainGUI’sdata. Ifthem
9 Managing and Sh aring Application Data in GUIDE...uiresume(handles.figure);Protecting and Positioning the Text Change Dialog1 The user opens the Tex
Making Multiple GUIs Work Togetherdisp('------------------------------ ----------------------- ');disp('Improper input arguments. Pass
9 Managing and Sh aring Application Data in GUIDEset(hObject, 'Position', [newX, newY, newW, newH]) ;...Initializing Text in the Text Change
Making Multiple GUIs Work Togetheruiresume(handles.figure);function fig ure_ CloseRequestFcn(hObject , ...eventdata, ha ndle s)uiresume(hObject);Apply
2 How to Create a GUI with GUIDEType of VideoVideo ContentMATLAB New FeatureDemosNew Graphics and GUI Building Features inVersion 7.6 (9 min, 31 s)New
9 Managing and Sh aring Application Data in GUIDEwait state; if it is, it ca lls uiresum e and returns, enabling the OutputFcnto be called:function fi
Making Multiple GUIs Work TogetherThese GUIs share data and expose functionality to one another using severaldifferent techniques:9-31
9 Managing and Sh aring Application Data in GUIDEView and Run the Three Icon Manipulation GUIsIf you are reading this in the M ATLAB Help browser, you
Making Multiple GUIs Work TogetherNote Do n o t save GUI files to the examples folder where you fo und them,or you will overwrite the original files.
9 Managing and Sh aring Application Data in GUIDEguide_iconeditor_OpeningFcn(hObject, eventdata, handles, varargin)varargout = guide_iconeditor_Output
Making Multiple GUIs Work TogethertoolPicker_CreateFcn(hObject, eventdata, handles)toolPalette_SelectionChangeFcn(hObject, eventdata, ha ndles)figure_
9 Managing and Sh aring Application Data in GUIDE...% Update handles structureguidata(hObject, h andles);The Color Palette nee ds to remember the Icon
Making Multiple GUIs Work Together...% Update handles structureguidata(hObject, h andles);Setting the Initial Color on the Color PaletteAfter you crea
9 Managing and Sh aring Application Data in GUIDEhandles.mSelectedColor =color;...guidata(hObject, handles);Call the publicized function from the Icon
Making Multiple GUIs Work Together..% Update handles structureguidata(hObject, handles);The Icon Editor retrieves the initial color from the Color Pal
Introduction to GUIDEAuthors add new tutorials to the set over time. Bo okmark this page andrevisit it occasionally to see them.Laying Out a GUIDE GUI
9 Managing and Sh aring Application Data in GUIDEguidata(hObject, handles);When you select the pencil tool and click in the icon-editing area, the Ico
Making Multiple GUIs Work Together...rows = size(handles.mIconCData, 1);cols = size(handles.mIconCData, 2);pt = get(handles.icon,'currentp oint&a
9 Managing and Sh aring Application Data in GUIDEYou cannot close the Co lo r Pale tte and Tool P a lette windows by directlyclicking their close butt
Making Multiple GUIs Work Togetherfunction fig ure_ CloseRequestFcn(hObject , eventdata, handle s)% Don't close this figure. It must be dele ted
9 Managing and Sh aring Application Data in GUIDE9-44
10Examples 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 E
10 Examples of GUIDE GUIsGUI with Multiple Axes (GUIDE)In this section...“About the Multiple Axes Example” on page 10-2“View and Run the M u ltip l e
GUI with Multiple Axes (GUIDE)Note You can create a more adv anced GUI that also displays time andfrequency plots by following the GUIDE example “GUI
10 Examples of GUIDE GUIs1 Click here to copy the files to your current folder.2 Type guide two_axes or click here to open the GUI in GU IDE.3 Type ed
GUI with Multiple Axes (GUIDE)• Frequency two (f2)• Atimevector(t)When the user clicks the Plot button, the GUI puts these values into aMATLAB express
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 hierarch
10 Examples of GUIDE GUIsTo create the default values, set the String property of the edit text. Thefollowing figure shows the value set for the time
GUI with Multiple Axes (GUIDE)The structure contains handles for all G UI components. You access thehandles using field names that GUIDE derives from
10 Examples of GUIDE GUIsGUI Option SettingsGUIDE has a set of preferences called GUI Options, available from the Toolsmenu. Two GUI Options settings
GUI with Multiple Axes (GUIDE)• Evaluating the time string using eval to produce a vector t,whichthecallback used to evaluate the mathematical expres
10 Examples of GUIDE GUIs• Providing the appropriate data to the plot function• Turning on the axes grid, w hich theplot function automatically turns
GUI with Multiple Axes (GUIDE)Validate User Input as NumbersGUI u sers type parameters into three edit text boxes as strings of text. Ifthey type an i
10 Examples of GUIDE GUIsif isnan(f1) || ~isreal(f1)% isdouble returns NaN for non-numbers and f1 cannot be complex% Disable the Plot button and chang
GUI with Multiple Axes (GUIDE)%tisnotanumberset(handles.plot_button,'String','t is not numeric')elseif length(t) < 2%tisnotavec
10 Examples of GUIDE GUIsIn this figure, the two p lots reflect the last successful set of inputs, f1 =31.41, f2 = 120,andt=[1234579].Thetimevector[12
GUI for Animating a 3-D View (GUIDE)GUI for Anim ating a 3-D View (GUIDE)In this section...“About the 3-D Animation Example” on page 10-15“ViewandRunt
About the S imple GUIDE GUI ExampleAbout the Simple GUIDE GUI ExampleIn this section...“Simple G UIDE GUI Components” on page 2-9“View Simple GUIDE GU
10 Examples of GUIDE GUIs• Start and stop the rotation.• Change lighting direction.• Display a latitude-longitude grid (or graticule).• Save the anima
GUI for Animating a 3-D View (GUIDE)the figure, the code, or both. Then you can save the G UI in your currentfolder using File > Save as from GUIDE
10 Examples of GUIDE GUIs• Static textThe Property Inspector was used to custom ize the uicontrols and text by:• Setting the figureColor to black, as
GUI for Animating a 3-D View (GUIDE)The GUI includes three uipanels that you can barely see in this figure becausethey are entirely black. Using uipan
10 Examples of GUIDE GUIsThe Show grid check box toggles the Visible property of the graticulesurface object. Theaxes1_CreateFcn initializes the grati
GUI for Animating a 3-D View (GUIDE)FunctionFunction Behaviorsunazslider_CreateFcnInitializes light source azimut hslider (not customized)sunelslider_
10 Examples of GUIDE GUIsstr = get(hObject,'String');state = find(strcmp(str,handles .Strings));set(hObject,'String',handles.Strin
GUI for Animating a 3-D View (GUIDE)example d oes not explore the technique, but you can find information aboutprogramming timers in “Using a MATLA B
10 Examples of GUIDE GUIsThe file name of the movie ends with the number o f frames it contains.Supposing the m ovie’s file name isglobe360.mat,youpla
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
2 How to Create a GUI with GUIDETo use the GUI, select a data set from the pop-up menu, then click one of theplot-type buttons. Clicking the button tr
10 Examples of GUIDE GUIsTexture and Color the GlobeCode in the ax es1_CreateFcn sets the CData for the globe to the 180-by-360(one degree)topo terrai
GUI for Animating a 3-D View (GUIDE)ThestateoftheShow grid button is initially off, causing the graticule notto display. Show grid toggles the mesh ob
10 Examples of GUIDE GUIsset(hgrotate,'Matrix',makehgtform(' zrotate',az));drawnow % Refresh the screenLight the Globe and Shift t
GUI for Animating a 3-D View (GUIDE)Further GraphicExplorationsYou can enhance the pre sentation ofglobegui in various ways, including:• Adding a colo
10 Examples of GUIDE GUIsTip Use a spherical grid that is the same size as topo to add terrain reliefto the globe. Then scale the values oftopo to wel
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
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 use
GUI to Interactively Explore Data in a Table (GUIDE)Note The tablestat example is based on the MATLAB sunspots demoand data set. Click here to view th
10 Examples of GUIDE GUIsNote Do not save GUI files to the examp les folder where you found themor you will overwrite the original files. If you want
GUI to Interactively Explore Data in a Table (GUIDE)Function NameFunction BehaviorGUIDE-Generated?plotPeriodGenerates plots (either time series orperi
Lay Out the Simple GUI in GUIDELay Out the Simple GUI in GUIDEIn this section...“Open a New GUI in the GUIDE Layout Editor” on page 2-11“Set the GU I
10 Examples of GUIDE GUIsPerform the following steps in GUIDE and in the P roperty Inspector togenerate the layout, thereby creating the follow ing ob
GUI to Interactively Explore Data in a Table (GUIDE)• A panel on the low er right, half the height of the first panel, renamingitsTitle to Data Statis
10 Examples of GUIDE GUIsb In the Property Inspector, click the Table Property Editor icon tothe right of theRowName property to open the Table Proper
GUI to Interactively Explore Data in a Table (GUIDE)5 Drag out a second axes, leaving its name as axes2 inside the Sunsp ots v.Year Plots pane l, dire
10 Examples of GUIDE GUIs• Double-click it and in the Property Inspector, set its Tag property to quitand its String property to Quit.• Click theCallb
GUI to Interactively Explore Data in a Table (GUIDE)6 From the list of workspace variables in the box below the radio button,selectsunspot and click O
10 Examples of GUIDE GUIsif ~isempty( peak )stats{9,col} = peak; % Peak period from FFTendNote When assigning data to a uitable, use a cell array, as
GUI to Interactively Explore Data in a Table (GUIDE)function plot_t ype_ Callback(hObject, e vent data, handles)% hObject handle to plot_type (see GCB
10 Examples of GUIDE GUIsRespond to Data SelectionsThe DataSettable has two columns: Year and Sunspots. The data tables’sCell Selection Callback analy
GUI to Interactively Explore Data in a Table (GUIDE)discontiguous rows to a selection. Because the Cell Sele ction Callback istriggered as long as the
2 How to Create a GUI with GUIDE2 In the GUIDE Quick Start dialog box, select the Blank GUI (Default)template. Click OK to display the blank GUI in th
10 Examples of GUIDE GUIsThis vector enumerates all the selected row s. If the selection includes lessthan 11 rows (as it does h ere) the callback ret
GUI to Interactively Explore Data in a Table (GUIDE)updates the Data Statistics table with the recomputed statistics. Here is thecode forrefreshDispla
10 Examples of GUIDE GUIs3 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
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 E
10 Examples of GUIDE GUIs% we want to do anything else to themhandles.axes1fig = axes1fig;handles.axes1copy = axes1copy;guidata(hObject,handles);The o
GUI to Interactively Explore Data in a Table (GUIDE)Upon Clicking Open plot in new window, a new figure is displayed withthe following content.10-51
10 Examples of GUIDE GUIsIt is the user’s responsibility to remove the new window when it is no longerneeded. The context menus can be programmed to d
GUI to Interactively Explore Data in a Table (GUIDE)- Provide a file dialog box or an input dialog box and code capable offiltering out nonnumeric, no
10 Examples of GUIDE GUIsList Box Directory Reader (GUIDE)In this section...“About the List Box Directory Example” on page 10-54“View and Run the L is
List Box Director y Reader (GUIDE)View and Run the List Box Directory GUIIf you are reading this document in the MATLAB Help browser, you canaccess th
Lay Out the Simple GUI in GUIDE3 Display the names of the GUI components in the component palette. SelectFile > Preferences. Then select GUIDE >
10 Examples of GUIDE GUIsNote Do not save GUI files to the examp les folder where you found themor you will overwrite the original files. If you want
List Box Director y Reader (GUIDE)% hObject handle to figure% eventdata reserved - to be defined in a future v ersion of MATLAB% handles structure wit
10 Examples of GUIDE GUIs• Use the dir command to get a list of files in the specified folder and todetermine which name is a folder and which is a fi
List Box Director y Reader (GUIDE)is a file, it is passed to the open command; if it is a folder, the GUI changesto that folder and lists its contents
10 Examples of GUIDE GUIsfile_list = get(handles.listbox1,' String');% Item selected in list boxfilename = file_list{index_selecte d};% If f
Access Workspace Variables from a List Box (GUIDE)Access Workspace Variables from a List Box (GUIDE)In this section...“About the Workspace Variable Ex
10 Examples of GUIDE GUIsView and Run the Workspace Variable GUIIf you are reading this document in the M ATLAB Help browser, you canaccess the exam p
Access Workspace Variables from a List Box (GUIDE)To just inspect the GUI in GUIDE and run it, follow these steps instead:1 Clickheretoaddtheexamplefi
10 Examples of GUIDE GUIsRead Selections from List BoxTheGUIrequirestheusertoselecttwovariablesfromtheworkspaceandthen choose one of three plot comman
Access Workspace Variables from a List Box (GUIDE)list_entries = get(handles.listbox1,'String');index_selected = get(handles.listbox1,'
2 How to Create a GUI with GUIDESet the GUI FigureSizeinGUIDESet the size of the GUI by resizing the grid area in the Layout Editor. Clickthe lower-ri
10 Examples of GUIDE GUIsA GUI to Set Simulink Model Parameters (GUIDE)In this section...“About the Simulink Model Parameters Example” on page 10-66“V
A GUI to Set Simulink®Model Parameters (GUIDE)The e xample illustrates a number of GUI building techniques:• Opening and setting parameters on a Simul
10 Examples of GUIDE GUIs2 Type guide f14ex or click here to open the FIG-file in G UID E.3 Type edit f1 4ex or click here to op en th e code file in
A GUI to Set Simulink®Model Parameters (GUIDE)F14 Controller Gain EditorYou can use the F14 Controller Gain Editor to analyze how changing thegains us
10 Examples of GUIDE GUIsThe graph is displayed in a figure, which is cleared e ach time you click thePlot button. The figure’s handle is hidden so th
A GUI to Set Simulink®Model Parameters (GUIDE)• Bring t he GUI forwa rd so it is display e d on t op of the Simulink diagrams(figure).• Set the block
10 Examples of GUIDE GUIs• Sets the value of the Current value edit text component to match theslider.• Sets the appropriate block parameter to the ne
A GUI to Set Simulink®Model Parameters (GUIDE)If the value is in range, the slide r Value property is updated to the newvalue.• Sets the appropriate b
10 Examples of GUIDE GUIs• Creates a structure to save the results of the simulation, the currentvalues of the simulation parameters set by the GUI, a
A GUI to Set Simulink®Model Parameters (GUIDE)if isequal(R esul tNum,1)ResultsStr = {['Run1',num2str(Kf), ' ',num2str(Ki)]};elseRe
Lay Out the Simple GUI in GUIDEAdd Components totheSimpleGUIDEGUI1 Add the three push buttons to the GUI. Select the push button tool fromthe componen
10 Examples of GUIDE GUIsif isequal(numResu lts,length(currentVal)),resultsStr = {'<empty>'};currentVal = 1;set([handles.RemoveButton,
A GUI to Set Simulink®Model Parameters (GUIDE)• Create an axes, set its Paren t property to the figure handle, and save theaxes handle.• Create the pl
10 Examples of GUIDE GUIsend% Plot datapHandles = plot(PlotData{:},'Parent',handles.PlotAxes);% Add a legend, and bring figure to the frontl
A GUI to Set Simulink®Model Parameters (GUIDE)function CloseB utto n_Callback(hObject, eventdata, handles)% Close the GUI and any plot window that is
10 Examples of GUIDE GUIsSet the Background to WhiteThe list box create function enables you to determine the background colorof the list box. The fol
An Address Book Reader (GUIDE)An Address Book Reader (GUIDE)In this section...“About the A ddress B ook Reader Example” on page 10-81“View and Run the
10 Examples of GUIDE GUIsThe example demonstrates the following GUI programm ing techniques:• Uses open and save dialog boxes to provide a means for u
An Address Book Reader (GUIDE)1 Click here to copy the files to your current folder.2 Type guide addr ess_ book orclickheretoopentheFIG-fileinGUIDE.3
10 Examples of GUIDE GUIs• Com mand-line accessib ility: Off• GUI O ptions selecte d:- Generate callback function prototypes- Application allows only
An Address Book Reader (GUIDE)% Load the default address boo kCheck_And_Load([],handles);% If the fi rst element in vara rgi n is 'book' and
2 How to Create a GUI with GUIDEArrange the components as shown in the following figure. Resize the axescomponent to approximately 2-by-2 inches.Align
10 Examples of GUIDE GUIs• Returns 1 for valid M AT-files and 0 if invalid (used by the Open menucallback).• Saves the following items in thehandles s
An Address Book Reader (GUIDE)end% If the file is valid, display itif pass% Add Addresses to the handles structurehandles.Addresses = data.Addresses;g
10 Examples of GUIDE GUIsFile = fullfile(pathname,filename) ;% if the M AT-f ile is not valid, do not save the nameif Check_And_Lo ad(F ile,handles)ha
An Address Book Reader (GUIDE)Contact Name Callbackfunction Contac t_Na me_Callback(hObject, eventdata, handles)% Get the strings in the Contact Name
10 Examples of GUIDE GUIs)set(handles.Contact_Phone,'String', Addresses(handles.Index) .Phone)returnendThe Contact Phone Number CallbackThe
An Address Book Reader (GUIDE)handles.Addresses = Addresses;guidata(hObject, handles)returncase 'Cancel '% Revert back to the original numbe
10 Examples of GUIDE GUIsis used in case statements to implem ent each button’s functionality (seethe code listing that follows).Paging Forward or Bac
An Address Book Reader (GUIDE)Current_Phone = Addresses(i).Phone;set(handles.Contact_Name,'string',C urrent_Name)set(handles.Contact_Phone,&
10 Examples of GUIDE GUIsSave_Callback Code Listingfunction Save_C allb ack(hObject, eventd ata, handles)% Get the Tag of the menu selectedTag = get(h
An Address Book Reader (GUIDE)The Address BookResize FunctionThe address bookdefines its own resize function. To use this resize function,you must set
Lay Out the Simple GUI in GUIDE3 Make these settings in the Alignment Tool, as shown in the following figure:• Left-aligned in the horizontal directio
10 Examples of GUIDE GUIsChange the HeightThe height a nd width of the figure is specified in pix el units. Usin g unitsof pixels enables maximizing a
An Address Book Reader (GUIDE)returnend% If resized figure is smal ler than original f igure then compensa te% However, do not change figure size if i
10 Examples of GUIDE GUIsUse a Modal Dialog Box to Con firm an Operation (GUIDE)In this section...“About the Modal Dialog Example” on page 10-98“View
Use a Modal Dialog Box to C onfirm an Operation (GUIDE)figure property WindowStyle determines whether it is modal or not. TypingCtrl+C changes a'
10 Examples of GUIDE GUIs2 ClickheretorunthemodalGUIs.3 ClickheretodisplaytheGUIsintheGUIDE Layout Editor (read only).4 Click here to display the GUI
Use a Modal Dialog Box to C onfirm an Operation (GUIDE)The GUI looks like the following figure.Note Modal dialog bo x es (figures with WindowStyle set
10 Examples of GUIDE GUIs8 Click the Show functions icon on the toolbar of the editor and selectclose_pushbutton_Callback from the drop-down menu.The
Use a Modal Dialog Box to C onfirm an Operation (GUIDE)When you click the Close button on the GUI, the m odal dialog box opens, asshown in the followi
10 Examples of GUIDE GUIsThis is an example of calling a GUI with a property value pair. In thiscase, the figure property is'Title', and its
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 th
2 How to Create a GUI with GUIDE4 Click OK. You r GUI n ow looks like this in the Layout Editor.Add Text to the ComponentsThe p ush buttons, p op-up m
10 Examples of GUIDE GUIsView and Run the GUIDE Timer GUIThis example contains link s to a FIG-file and a code file that MA TLABdocumentation provides
Time Data Updates from a GUI (GUIDE)2 Type guide ex_guide_timergui in the C ommand Window or click hereto open the GUI in GUIDE.3 Open the G UI co de
10 Examples of GUIDE GUIsthe link in the Callback column. You cannot access the timer object fromwithin GUIDE; it is created programmatically.Componen
Time Data Updates from a GUI (GUIDE)How the GUI Implements the TimerEach callback inthe G UI either creates, m odifies, starts, stops, or destroysthe
10 Examples of GUIDE GUIsstartbtn_Callbackstartbtn_Callback calls timer start m ethod if the timer is not alreadyrunning:if strcmp(get(h andl es.timer
Time Data Updates from a GUI (GUIDE)update_displayupdate_display is the callback for the timer object. It adds Gaussian noise totheZData ofthesurfacep
10 Examples of GUIDE GUIsOther Uses for Timers in GUIsIn addition to acquiring or processing data at regular intervals, you can usetimers to implement
Create GUIs ProgrammaticallyChapter 11, Lay Out aProgrammatic GUI (p. 11-1)Shows you how to createand organize the GU I codefile and from there how to
11Lay Out a ProgrammaticGUI• “Design a Programmatic GUI” on page 11-2• “Create and Run a Programmatic GUI” on page 11-4• “Create Figures for Program m
Lay Out the Simple GUI in GUIDEAfter you have added the appropriate text, the GUI will look like this in theLayout Editor.Label the Push Buttons. Each
11 Lay Out a Programmatic GUIDesign a Programmatic GUIBefore creating the actual GUI, it is important to decide what it is you wantyour GUI to do and
Design a Programmatic GUIMany Web sites and commercial publications such as th e followin g provid eguidel ines for design ing GUIs:• AskTog — Essays
11 Lay Out a Programmatic GUICreateandRunaProgrammaticGUIIn this section...“File Organization” on page 11-4“File Template” on page 11-4“Run the GUI” o
CreateandRunaProgrammaticGUI% to the help co mman d.% (Leave a blank line follo wing the help.)% Initialization tasks% Construct th e components% Init
11 Lay Out a Programmatic GUICreate Figures for Programmatic GUIsIn MATLAB software, a GUI is a figure. B efore you add components to it,create the fi
Create Figures for Programmatic GUIsProperty Values DescriptionResizeon, off.Defaultison. Determines if the user canresize the figure window w iththe
11 Lay Out a Programmatic GUIThe Position property is a four-element vecto r that spe cifies the location ofthe GUI on the screen and its size: [dista
Add Components to a Programmatic GUIAdd Components to a Programmatic GUIIn this section...“Types of G UI Components” on page 11-9“Add User Interface C
11 Lay Out a Programmatic GUIComponent Function DescriptionActiveXactxcontrolActiveX components enable you todisplay ActiveX controls in yourGUI. They
Add Components to a Programmatic GUIComponent Function Description“Panel” on page11-35uipanelPanels arrange GUI components intogroups. By vis ually gr
ContentsIntroduction to Creating GUIsAbout GUIs in MATLAB S oftware1What Is a GUI? ... 1-2How Does a GUI Work?...
2 How to Create a GUI with GUIDE2 In the layout area, select the top push button by clicking it.3 In the Property Inspector, select the String propert
11 Lay Out a Programmatic GUIComponent Function Description“Slider” on page11-28uicontrolSliders accept numeric input withina specified range by enabl
Add Components to a Programmatic GUIComponent Function Descriptiongrouptomanagemutuallyexclusiveradio buttons.Toolbar Buttonsuitoolbar,uitoggletool,ui
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
Add Components to a Programmatic GUIProperty Values DescriptionStringString. C an be a cellarray or character array orstrings.Component label. For lis
11 Lay Out a Programmatic GUIcbh = uicontrol(fh,'Style','checkb ox',...'String','Display file extension ',...&
Add Components to a Programmatic GUINote You can also use an image as a label. See “Add an Image to a PushButton” on page 11-26 for more information.E
11 Lay Out a Programmatic GUIIf Max-Min is less than or equal to 1, the edit text component admits only asingle line ofinput. If you specify a com po
Add Components to a Programmatic GUIfont =FontName: 'Century Schoolbook'FontWeight: 'normal'FontAngle: 'normal'FontSize:
11 Lay Out a Programmatic GUIInstead of d esignating a font yourself, you could provide a push button orcontext menu in your GUI that allows users to
Add Components to a Programmatic GUIString PropertyFormatExampleCell array of strings{'one' 'two' 'three'}Padded s tring
Lay Out the Simple GUI in GUIDE5 Select each of the remaining push buttons in turn and repeat steps 3 and 4.Label the middle push button Mesh, and the
11 Lay Out a Programmatic GUIIf the list box is not large enough to display all list entries, you can set theListBoxTop property to the index of the i
Add Components to a Programmatic GUIThe Str ing property defines the menu items. You can specify the items inany of the formats shown in the following
11 Lay Out a Programmatic GUITableThe following code creates a table with handle th. It populates it with thematrixmagic(5), and then adjusts its size
Add Components to a Programmatic GUI• Foreground and background colors.• Row striping.• Row labels/numbers.• Column labels/numbers.• Column formats an
11 Lay Out a Programmatic GUIThe Style property, pushbutton, specifies the user interface control as a pushbutton. Becausepushbutton is the default st
Add Components to a Programmatic GUINote Create your own i con with the icon editor described in “Icon Editor”on page 15-63. Seeind2rgb for informatio
11 Lay Out a Programmatic GUIThe Value property specifies w hether the radio button is selected when thecomponent is created. SetValue to the value of
Add Components to a Programmatic GUI• Specify the value indicated by the slider when it is created by setting theValue property to the appropriate num
11 Lay Out a Programmatic GUINote On Mac p latforms, the height of a horizo ntal s lide r is co n strained. Ifthe height you set in the position vecto
Add Components to a Programmatic GUIThe Position property specifies the lo cation and size of the static textcomponent. In this exam ple, the static t
2 How to Create a GUI with GUIDE3 Replace the existing text with the names of the three data sets: Peaks,Membrane, and Sinc. Press Enter to move to th
11 Lay Out a Programmatic GUIaccommodate the s pe cified String, MATLAB software truncates the stringwith an ellipsis.The Value property specifies whe
Add Components to a Programmatic GUIAsyntaxforpanelsisph = uipanel(fh,'PropertyName',Pro pertyValue,...)where ph is the handle of the result
11 Lay Out a Programmatic GUIProperty Values DescriptionParentHandleHandle of the component’s parentfigure, panel, or button group.Position4-element v
Add Components to a Programmatic GUIPanelThe following statement creates a panel w ith handle ph.Useapaneltogroupcomponents in the GUI.ph = uipanel(&a
11 Lay Out a Programmatic GUIfigure and 10 percent of the figure height from the bottom. As the figure isresized the panel retains these proportions.T
Add Components to a Programmatic GUIThe Parentproperty specifies the handle fh of the parent figure. You can alsospecify the parent as a panel o r but
11 Lay Out a Programmatic GUI'Position',[.1 .6 .3 .2]);rbh2 = uicontrol(bgh,'Style','r adiobutton','String',&a
Add Components to a Programmatic GUI• “Axes” on page 11-39Commonly Used PropertiesThe most commonly used properties n eeded to describe an axes are sh
11 Lay Out a Programmatic GUIah = axes('Parent',fh,'Position',[ .15 .15 .7 .7]);The Parent property specifies the handle fh of the
Add Components to a Programmatic GUIThe s oftware automatically adds the tick marks. Most functions that drawin the axes u pdate the tick marks approp
Lay Out the Simple GUI in GUIDE3 Click OK .ThephraseSelect Data appears in the static text componentabove the pop-up menu.Completed Simple GUIDE GUI L
11 Lay Out a Programmatic GUICompose and Code GUIs with Interactive ToolsIn this section...“Set Positions of Components Interactively” on page 11-43“A
Compose and Code GUIs with Interactive ToolsSome of thes e tools return property valu e s, while others let you edit propertiesinteractively without r
11 Lay Out a Programmatic GUI4 Make sure that you know the handle of the component you havemanipulated. In the following code, the handle is a variabl
Compose and Code GUIs with Interactive Toolsrect = get(handle,'Position');inspect(handle)To experiment with the function, enter the followin
11 Lay Out a Programmatic GUIUsePlotEditModetoChangePropertiesAfter you select an object in plot edit mode, you can open the PropertyInspector to view
Compose and Code GUIs with Interactive ToolsScroll in the help window to view descriptions of other properties. Click the Xclose box to close the w in
11 Lay Out a Programmatic GUIshows the Backgrou ndCo lor and S tring properties of a list box altered usingthe Property Editor.Most of the properties
Compose and Code GUIs with Interactive ToolsYou can obtain the new property value by running the ge t function:value = get(object_handle, 'Proper
11 Lay Out a Programmatic GUIset(object_handle,'Position',rect)set(object_handle,'Units',myunits)elserect = [];endclipboard('
Compose and Code GUIs with Interactive Tools3 Release the mouse button. The control moves.4 The button Position is set, returned and placed on the sys
2 How to Create a GUI with GUIDE2-24
11 Lay Out a Programmatic GUIbtn1 = uicontrol('Style','pushbutt on',...'String','Push Me','Position'
Compose and Code GUIs with Interactive Tools5 Place your cursor between the empty brackets and type Ctrl+V,orright-click and select Paste. Allowing fo
11 Lay Out a Programmatic GUIalso distribute the components evenly across their span or specify a fixeddistance between them.A syntax for thealign fun
Compose and Code GUIs with Interactive ToolsNote Each of the three following align examples starts with these unalignedpush buttons and repositions th
11 Lay Out a Programmatic GUIAlign Com ponents Vertically W hile Distributing Them Ho rizontally.The following statement moves the push buttons to the
Compose and Code GUIs with Interactive ToolsUseAlignDistributeToolsIf your figure has a standard menu bar, y ou can perform align and distributeoperat
11 Lay Out a Programmatic GUIThe following steps illustrate how to use the Align Distribute tool to arrangecomponents in a GUI. The tool provides the
Compose and Code GUIs with Interactive ToolsThe buttons align as shown.Note One thing to remember w hen aligning components is that the alig nfunction
11 Lay Out a Programmatic GUIFor more information, see “Ali gn/Distribute Menu Optio ns”.Set Colors InteractivelySpecifying colors for Color, Foregrou
Compose and Code GUIs with Interactive Toolsof colors. The uisetcolor function opens a GUI that returns color valuesyou can plug into components when
Save the GUI LayoutSave the GUI LayoutWhen you save a GUI, GUIDE creates two files, a FIG-file and a code file. TheFIG-file, with extension.fig, is a
11 Lay Out a Programmatic GUISet Font Characteristics InteractivelyThe uisetfont GUI gives you access to the characteristics of all fonts on yoursyste
Compose and Code GUIs with Interactive Tools'String',inputdlg('String','Static Text'),...uisetfont,'Position',
11 Lay Out a Programmatic GUIGenerate Code to Set Component PropertiesThe techniques described in the preceding s ections set properties ofcomponents
Compose and Code GUIs with Interactive ToolsHelp system that contains doc examples. See “View and Run the setpropFunction” on page 11-68. Property val
11 Lay Out a Programmatic GUIfor the current value of the property, or '' for an invalidproperty nam e.setstr = setprop(objhandle,prop erty,
Compose and Code GUIs with Interactive Toolssetprop(object_handle,'pos')ans =set(object_handle,'Position',[20 20 60 20])If you omi
11 Lay Out a Programmatic GUITip You can provide an empty property name followed by a value when youcallsetprop. Then, the function attempts to assign
Compose and Code GUIs with Interactive Tools1 Click here to add all GUI example files to the M ATLAB path (only for thecurrent session).2 Type edit se
11 Lay Out a Programmatic GUISet Tab Order in a Programmatic GUIIn this section...“How Tabbing Works” on page 11-70“Default Tab O rder” on page 11-70“
Set Tab Order in a Programmatic GUI'String',{'peaks','membrane','sinc'},. ..'Position',[290 200 130
2 How to Create a GUI with GUIDE4 Browse to any folder for which you have write privileges, and then enterthe filenamesimple_gui for the FIG-file. GUI
11 Lay Out a Programmatic GUIwhere ph is the handle of the panel. This statement returns a vectorcontaining the handles of the children, the three pus
Set Tab Order in a Programmatic GUIChange the Tab OrderUse the uist ack function to change the tab order of components that have thesame parent. A con
11 Lay Out a Programmatic GUINote Tab order also affects the stacking order of components. If componentsoverlap, those that appear low er in the child
Create Menus for a Programmatic GUICreate Menus for a Programmatic GUIIn this section...“Add Menu Bar Menus” on page 11-75“Add Context Menus to a Prog
11 Lay Out a Programmatic GUIIf you use the standard menu bar menus, any menus you create are added toit. If you choose not to display the standard me
Create Menus for a Programmatic GUIProperty Values DescriptionHandleVisibilityon, off. Default ison.Determines if an object’s handleis visible in its
11 Lay Out a Programmatic GUIFigure windows with a standard menu bar also have a Desktop menu fromwhich the user can dock and undock them.To display t
Create Menus for a Programmatic GUIMenu Bar MenuThe following statements create a menu bar menu with two menu items.mh = uimenu(fh,'Label',&
11 Lay Out a Programmatic GUIThe following statement adds a separator line preceding the second menuitem.set(eh2,'Separator','on')
Create Menus for a Programmatic GUINote After you have created all menu items, set their HandleVisibilityproperties off by executing the following sta
Save the GUI LayoutTo run a GUI created with G UID E without opening GUIDE, execute its codefile by typing its name.simple_guiYou can also use the run
11 Lay Out a Programmatic GUIProperty Values DescriptionHandleVisibilityon, off. Default ison.Determines if an object’s handle is visible inits parent
Create Menus for a Programmatic GUIfh = figure('Position',[300 300 400 225]);cmenu = uicontextmenu('Parent', fh,'Position&apo
11 Lay Out a Programmatic GUIYou can use any applicable Uimenu Properties such as C heck ed or Separatorwhen you define context menu items. See the ui
Create Menus for a Programmatic GUIThis code associates the context menu with the figure and with the axes bysetting theUIContextMenu property of the
11 Lay Out a Programmatic GUIRight-click on the figure or on the axes. The context menu appears with itsupper-left corner at the location you clicked.
Create Menus for a Programmatic GUIThe context menu is displayed 10 pixels from the left of the figure and 215pixels from the bottom.If you set the co
11 Lay Out a Programmatic GUICreate Toolbars for Programmatic GUIsIn this section...“Use the u itoolbar Function” on page 11-88“Commonly Used Properti
Create Toolbars for Programmatic GUIsProperty Values DescriptionCData3-D array of valuesbetween 0.0 and 1.0n-by-m-by-3 array o f RGBvalues that define
11 Lay Out a Programmatic GUIimg1(:,:,1) = repmat(a,16,1)'img1(:,:,2) = repmat(a,16,1);img1(:,:,3) = repmat(flipdim(a,2),16,1);pth = uipushtool(t
Create Toolbars for Programmatic GUIsTooltipString specifies the tooltips for the push tool and the toggle too l asMy push tool and Your toggle tool,r
2 How to Create a GUI with GUIDEProgram the Simple GUIDE GUIIn this section...“Add Code to the Simple GUIDE GUI” on page 2-28“Generate Data to Plot” o
11 Lay Out a Programmatic GUINote After you have created a toolbar and its tools, set theirHandleVisibility properties of f by executing statements si
Create Toolbars for Programmatic GUIsModify the Standard ToolbarOnce you have the handle of the standard toolbar, you can add tools, deletetools, and
11 Lay Out a Programmatic GUIDesign Programmatic GUIs for Cross-PlatformCompatibilityIn this section...“Default System Font” on page 11-94“Standard Ba
Design Programmatic GUIs for Cross-Platform CompatibilityUse a Specific Font NameYou can specify an actual font name (such as Times or Courier) for th
11 Lay Out a Programmatic GUIThe following figures illustrate the results with and without system colormatching.Cross-Platform Compatible UnitsCross-p
Design Programmatic GUIs for Cross-Platform CompatibilityResizeFcn enables you to customize the GUI’s resize behavior and is validonly if you setResiz
11 Lay Out a Programmatic GUINorm alized. Normalized units represent a percentage of the size of theparent. The value of normalized units lies between
12Code a Programmatic G UI• “Organize a Programmatic GUI File” on page 12-2• “Initialize a Programmatic GUI” on page 12-3• “Write Code for Callbacks”
12 Code a Programmatic GUIOr ganize a Programmatic GUI FileAfter laying out your GUI, program its behavior. This chapter addresses theprogramming of G
Initialize a Programmatic GUIInitialize a Programmatic GUIWhen you open a GUI, it usually initializes certain data structures andvariable values. Thes
Program the Simple GUIDE GUIThe cursor moves to the opening function, which already contains this code:% --- Executes just before simple_gui is made v
12 Code a Programmatic GUIExamplesIf you are reading this in the MATLAB Help Browser, use the following linksto view the complete code files for th e
Initialize a Programmatic GUIThe fullfi le function builds a full filename fr om parts.The following statements each start the Icon Editor. The first
12 Code a Programmatic GUIMost components have Visible properties. You can also use these propertiesto make individual components invisible.Return Out
WriteCodeforCallbacksWrite Code for CallbacksIn this section...“What Is a Callback?” on page 12-7“Kinds of Callbacks” on page 12-8“Specify Callbacks i
12 Code a Programmatic GUIKindsofCallbacksThe GUI figure and each type of component has specific kinds of callbackswith which you can associate it. Th
WriteCodeforCallbacksCallback Property Triggering Event ComponentsClickedCallbackControl action. Executeswhen the push tool ortoggle tool is clicked.
12 Code a Programmatic GUICallback Property Triggering Event ComponentsResizeFcnExecutes when a userresizes a panel, buttongroup, or figure whosefigur
WriteCodeforCallbacksNote User interface controls include push buttons, sliders, radio buttons,check boxes, editable text boxes, st atic text boxes, l
12 Code a Programmatic GUIYou can attach a callback when you create a component by supplying thecallback’s property name and value (its calling sequen
WriteCodeforCallbacksYou can concatenate commands in a string callback. This one, for example,adds a title to the plot it creates.set(hb,'Callbac
Save the GUI Layout ... 2-25Program the Simple GUIDE GUI... 2-28Add Code to the Simple GUIDE GUI...
2 How to Create a GUI with GUIDE% uiwait(handles.f igure1);2 Create data for the GUI to plot by adding the following code to the openingfunction immed
12 Code a Programmatic GUIfunction displa y_sl ider_value(hObject,even tdata)disp(['Slider moved to ' num2str(get(hObject,'Valu e'
WriteCodeforCallbacksthat you specify. Place single quotes around the function name and any literalstring arguments, but not around workspace variable
12 Code a Programmatic GUIfunction pushbu tton _callback(hObject, eventdata, var1, va r2)plot(var1,var2)When you run this GUI by pressing the push but
WriteCodeforCallbacksUse Cell Arrays with Function Handles. You can specify a callbackfunction using a function handle instead of using a function nam
12 Code a Programmatic GUINote Unless you declare them as string s (with required arguments, asdescribed in “Use String Callbacks” on page 12-12), do
WriteCodeforCallbacksGUI ComponentCallbacks with EventDataProperty ReferencePagesFigureKeyPressFcn,KeyReleaseFcn,WindowKeyPressFcn,WindowKeyReleaseFcn
12 Code a Programmatic GUIExamples: Program GUI ComponentsIn this section...“Program User Interface Controls” on page 12-20“Program Panels and Button
Examples: Program GUI C omponentsCheck BoxYou can determine the current state of a check box from within any of itscallbacks by querying the state of
12 Code a Programmatic GUIRetrieve Numeric Data from an Edit Text Component. MATLA Bsoftware returns the value of the edit textString property as a ch
Examples: Program GUI C omponents• Ctrl+V –Paste• Ctrl+H – Delete last character• Ctrl+A – Select allList BoxWhen the list box Callback callback is tr
Program the Simple GUIDE GUIProgram the Pop-Up MenuThe pop-up menu enables the user to select the data to plot. When the GUIuser selects one of the th
12 Code a Programmatic GUIopen on the second click. The callback can query the figure Sel ectionTypeproperty to determine if it was a single or d oubl
Examples: Program GUI C omponentsYou can also select a menu item programm atically by setting the pop-upmenuValue property to the index o f the desire
12 Code a Programmatic GUIclose(gcbf)gcbfreturns the handle of the figure containing the object whose callbackis executing.Radio ButtonYou can determi
Examples: Program GUI C omponentsslider_value = get(hObject,'Value');% Proceed with callback...The Max an d Min properties specify the slide
12 Code a Programmatic GUINote You can use a button group to m anage exclusive selection behavior fortoggle buttons. See “B utton Group” on page 12-28
Examples: Program GUI C omponentsset of radio buttons, toggle buttons, or both, the button group allows only oneof them to be selected. When a user cl
12 Code a Programmatic GUIThe button group Sele ctionChangeFcn callback is called whenever a selectionis made. If you have a button group that contain
Examples: Program GUI C omponentsProgram AxesAxes components enable your GUI to display graphics, such as graphs andimages. This topic briefly tells y
12 Code a Programmatic GUI2 Run the GUI by typing two_axes at the command line. This is what theexample looks like before you click the push buttons.3
Examples: Program GUI C omponentsSee “GUI with Multiple Axes (GUIDE)” on page 10-2 for a more complexexample that uses two axes.If your GUI contains a
2 How to Create a GUI with GUIDEIf the editor is not already open, GUIDE opens it to display the GUIcode file, and the cursor moves to the pop-menu ca
12 Code a Programmatic GUI• Properties that you can set to control many aspects of axes behavior andappearance, see “Axes Objects — Defining Coordinat
Examples: Program GUI C omponentsWhen a user selects Edit > Copy > to file,noCopy callback is needed toperform the action. Only theCallback call
12 Code a Programmatic GUIOpen a Dialog Box from a Menu CallbackThe Callback callback for the to file menu item could contain code such asthe followin
Examples: Program GUI C omponentsUse of checks when the GUI is first displayed should be consistent with thedisplay. For example, if your GUI has an a
12 Code a Programmatic GUI2 Click the push tool to display the color selection dialog box and click acolor to s elect it.3 Click OK on the color selec
Examples: Program GUI C omponentsNote Create your own icon with the icon editor described in “Icon Editor” onpage 15-63. See theind2rgb reference page
12 Code a Programmatic GUI1 Copy the f ollowing code into a file and save it in your current fo lderor on your path astoggle_plots.m. Execute the func
Examples: Program GUI C omponents12-41
12 Code a Programmatic GUI2 Click the toggle tool to display the initial plot. The counter increments to 1.3 Continue clicking the toggle tool to togg
13ManageApplication-Defined Data• “Ways to Manage Data in a Program m atic GUI” on page 13-2• “Share Data Among a GUI’s Callbacks” on page 13-11
Program the Simple GUIDE GUIIt then uses a switch statement to make the selected data set the currentdata. The last statement saves the changes to the
13 Manage Application-Defined DataWays to Manage Data in a Programmatic GUIIn this section...“Data Management Mechanis m Summary” on page 13-2“Nested
Ways to Manage Data in a Programmatic GUIData-SharingMethodHow it WorksUse for...Pass function handlesor data through oneof the four followingmethods:
13 Manage Application-Defined Data• Nested Functions — Share variables defined at a higher level and callone another when called function is below abo
Ways to Manage Data in a Programmatic GUISee “Share Data with Nested Functions” on page 13-11 for a completeexample.UserData PropertyAll GUI component
13 Manage Application-Defined DataSee “Share Data with UserData” on page 13-15 for a complete example.Application DataApplication data is data that is
Ways to Manage Data in a Programmatic GUICreate Application DataUse the setappdata function to create application data. This examplegenerates a 35-by-
13 Manage Application-Defined DataGUI DataMost GUIs generate or use data that is specific to the application. Thesemechanisms provide a way for applic
Ways to Manage Data in a Programmatic GUIautomatically passed to each callback as hObject. S ee “Specify Callbacks inFunction Calls” on page 12-11 for
13 Manage Application-Defined DataNote To use hObject, you must specify a component’s callback propertiesas function handles. When you do, the compone
Share Data Among a GUI’s CallbacksShare Data Among a GUI’s CallbacksIn this section...“Share Data with Nested Functions” on page 13-11“Share Data with
2 How to Create a GUI with GUIDE1 Display the Surf push button callback in the MATLAB Editor. Right-clickthe Surf push button in the Layout Editor to
13 Manage Application-Defined DataThe GUI behavior is as follows:• When a user moves the slider, the edit text component displays the slider’scurrent
Share Data Among a GUI’s Callbacks'Callback',@slider_callback);eth = uicontrol(fh,'Style','edi t',...'String',
13 Manage Application-Defined Datanum2str(number_errors),' times.']);val = previous_val;endendendBecause the components are constructed at t
Share Data Among a GUI’s Callbacks• num2 str converts the value to a string.•set sets the String property of the edit text component to the updatedval
13 Manage Application-Defined DataUserData Property Example: Passing Data BetweenComponentsThefollowingcodeisthesameasinthepriorexample,“ShareDatawith
Share Data Among a GUI’s Callbacksset(eth,'String',num2str(slider.val) );sprintf('You changed the slider value by %6.2f percent.',
13 Manage Application-Defined DataSlider Values. In this example, both the slider callback, slider_callbac kand the edit text callback, edittext_callb
Share Data Among a GUI’s Callbacksfunction slider _gui _appdatafh = figure('Position',[250 250 350 350],...'MenuBar','none&ap
13 Manage Application-Defined Dataslider_data.previous_val = slide r_data.val;slider_data.val = str2double(get(hObject,'String'));% Determin
Share Data Among a GUI’s CallbacksBoth callbacks use the getappdat a and s etappdata functions to retrieve andsave theslider_data structure as sl ider
Program the Simple GUIDE GUI3 Repeat steps 1 and 2 to add similar code to the Mesh and Contour pushbutton callbacks.• Add this code to the Mesh push b
13 Manage Application-Defined Data% ---------- ---- ----------------------- ---------------% Set the value of the edit text component String property%
Share Data Among a GUI’s CallbacksSlider Values. In this example, both the slider callback, slide r_c allback,and the edit text callback,edittext_call
13 Manage Application-Defined Data13-24
14Manage Callback Execution
14 Manage Ca llback Executio nCallback Sequencing and InterruptionIn this section...“Control C allback Execution and Interruption” on page 14-2“Contro
Callback Sequencing and InterruptionNote For information about what callbacks are and do, see “Write Code forCallbacks” on page 12-7 in this User’s Gu
14 Manage Ca llback Executio n3 KeyPressFcn (uicontrol and uitable callback)4 KeyReleaseFc n (in f ig ure window only)5 WindowKeyRel ease Fcn (in figu
Callback Sequencing and Interruption- WindowButton DownFcn- WindowButton MotionFcn- WindowButton UpFcn- WindowScroll WheelFcnFor callbacks that object
14 Manage Ca llback Executio nis taken into account only if the Inter ruptible property of the executingcallback’s object isoff, i.e., the executing c
Callback Sequencing and InterruptionThis code creates the two Wait butto n s and specifies th e callbacks thatservice them.h_interrupt = uicontrol(h_p
2 How to Create a GUI with GUIDEUsetheCompletedSimpleGUIDEGUIOpen and Run the GUIIn “Program the Simple GUIDE GUI” on page 2-28, you programmed thepop
14 Manage Ca llback Executio nThis code creates the two plot buttons and specifies the callbacks thatservice them.hsurf_queue = uicontrol(h_panel2,&ap
Callback Sequencing and InterruptionNote This link executes MATLAB commands and is designed to work withinthe M ATLA B Help browser. If you are readin
14 Manage Ca llback Executio n% Enable the other push butto nset(h_noninterrupt,'Enable','on')endThe callback first disables the o
Callback Sequencing and Interruptionh_plot = surf(h_axes2,peaks_data) ;endViewtheCompleteGUICodeFile.If you are reading this in the MATLABHelp browser
14 Manage Ca llback Executio ndelete the timer before your GUI closes. To start a timer, call its st artmethod. The tim er executes its StartF cn, beg
15Examples of GUIs CreatedProgrammatically• “Techniques Explored by Programmatic GUI Examples” on page 15-2• “GUI with Axes, Menu, and Toolbar” on pag
15 Examples of GUIs Created ProgrammaticallyTechniques Explored by Programmatic GUI ExamplesThefivecompleteexamplesthatfollowillustratehowtocreateandp
Techniques Explored by Programmatic GUI ExamplesFor information about programming specific types of components, see“Examples: Program GUI Components”
15 Examples of GUIs Created ProgrammaticallyGUI with Axes, Menu, and ToolbarIn this section...“About the Axes, Menu, and Toolbar Example” on page 15-4
GUI with Axes, Menu, and ToolbarWhen you run the GUI, it initially displays a plot of fiv e random numbersgenerated by the MATLAB commandrand(5) comma
UsetheCompletedSimpleGUIDEGUIgive a GUI docking controls, but it must display a menu bar or a toolbarto enable them. For more information, see “How Me
15 Examples of GUIs Created ProgrammaticallyThe GUI toolbar has two buttons:• The Open buttonperforms the same function as the Open menu item. Itdispl
GUI with Axes, Menu, and Toolbar3 edit ico nRea d.m or Click he re to open the utility iconRead file in theEditor .If you just want to run the GUI and
15 Examples of GUIs Created Programmatically'plot(membrane)', @(a)plot(a,membrane);'surf(peaks)', @(a)surf(a,peaks)};Because the d
GUI with Axes, Menu, and Toolbar• Setting the HandleVisib ility property to callback ensures that thefigure can be accessed only from within a GUI cal
15 Examples of GUIs Created ProgrammaticallySee the Axes Properties reference page for information about axes propertiesand their default values.The P
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 stringUpdate.• Sett
15 Examples of GUIs Created Programmaticallyit the child of the main figure. This statement creates a m enu bar in thefigure and puts the File menu on
GUI with Axes, Menu, and Toolbar• The uipusht ool function creates the two push buttons on the toolbar.• The uipushtoolTooltipString property assigns
15 Examples of GUIs Created ProgrammaticallyDefine the CallbacksThis topic defines the callbacks that service the components of the GUI.Because the ca
GUI with Axes, Menu, and ToolbarNote MATLAB software automatically passes hUpdateButtonCallbacktwo arguments, hObjec t and ev entd ata,becausetheUpdat
2 How to Create a GUI with GUIDE2-38
15 Examples of GUIs Created ProgrammaticallyThe hOpenM enu itemCallback function first calls the uigetfile function toopen the standard dialog box for
GUI with Axes, Menu, and ToolbarThe hPrintMenuitemCallback function calls the printdlg function. Thisfunction opens the standard system dial o g box f
15 Examples of GUIs Created Programmaticallydelete(hMainFigure);endThe hCloseMenuite mCal lback function calls the questdlg function to createand open
GUI that Displays and Graphs Tabular DataGUI that Displays and Graphs Tabular DataIn this section...“About the tableplot Example” on page 15-19“View a
15 Examples of GUIs Created ProgrammaticallyPlot columnsuitable withnamed columnsAxes withx- and y-labelsInitial promptThe table displays MATLAB sampl
GUI that Displays and Graphs Tabular DataThe tableplot main function creates a GUI figure with the following UIcomponents:• A uitable w ith three colu
15 Examples of GUIs Created ProgrammaticallyUIObjectHandle Callback Type Callback Signature RemarksCheckbox—Callback {@plot_callback,3}Plots a line gr
GUI that Displays and Graphs Tabular DataThe circle markers appear and disappear dynamically as the user selects cellsin the table. You do not need to
15 Examples of GUIs Created ProgrammaticallyPDF, go to the corresponding section in the MATL AB Help Browser to usethe links.If you intend to modify t
GUI that Displays and Graphs Tabular DataThe main tableplot function sets up the uitable is immediately after loadingadatamatrixintotheworkspace. Thet
3How to Create a SimpleGUI Programmatically• “About the Sim ple Programmatic GUI Example” on page 3-2• “Create the Simple Programmatic GUI Code File”
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
GUI that Displays and Graphs Tabular Data% Callback to erase and replot markers, showing only those% corresponding to user-selected cells in table.% R
15 Examples of GUIs Created Programmatically3233If rows 5, 6, and 7 of columns 2 and 3 are selected,eventdata =Indices: [6x2 double]sel =525362637273A
GUI that Displays and Graphs Tabular Data• htab le — To fetch table data and column names for plotting the dataand deleting lines; thecolumn argument
15 Examples of GUIs Created ProgrammaticallyendendSubfunction Summary for tableplotThe tableplot ex ample conta in s the callbacks l isted in th e fol
GUI that Displays and Graphs Tabular Data• Parsecommand-lineargumentsspecifyingaworkspacevariabletoloadinto the table when the GUI opensIftheuserspeci
15 Examples of GUIs Created ProgrammaticallyThe data matrix might have colum ns with very different data ranges andunits of measure. Therefore, one ch
A GUI That Manages List DataAGUIThatManagesListDataIn this section...“About the List Master Example” on page 15-33“View and Run the List Master Code”
15 Examples of GUIs Created ProgrammaticallyAn empty List Master GUI A List Master GUI with Controls and DataThe ComponentsA new List Master GUI figur
A GUI That Manages List Data- A list box, displaying an imported list- Three push buttons that respectively• M ove the selected item higher in the cur
Create GUIs with GUIDEWhat Is GUIDE?4GUIDE: Getting Started ... 4-2GUI Layout... 4-2GUI Pr
3 How to Create a Simple GUI ProgrammaticallyAbout the Simple Programmatic GUI ExampleSimple Programmatic GUI ComponentsThis section shows you how to
15 Examples of GUIs Created Programmatically• Automatically number list items and renumber them as needed (or not)• Give seve ral uicontrols the same
A GUI That Manages List DataIf you just want to run the GUI and inspect its code, follow these steps:1 ClickheretoaddtheexamplefilestotheMATLABpath(on
15 Examples of GUIs Created Programmatically3 TypeanameforthelistyouwanttocreateandclickOK.Ifyouwanttousethesampledataprovidedwiththisexample,youcanca
A GUI That Manages List DataFigure name Panel withlist nameSelectedlist itemEditablelist itemMove itemdown upToggle listnumberingDelete listitemEdit
15 Examples of GUIs Created ProgrammaticallyNote A List Master GUI has no facility to rename itself should someonereplace its contents. You can easily
A GUI That Manages List Data1 Click on the list box item you want to copy or select the item’s text in theedit box.2 Type Ctrl+C to copy the item.3 Op
15 Examples of GUIs Created ProgrammaticallyProgram List MasterThe List Master GUI code file contains 22 functions, organized into fivegroups.• “List
A GUI That Manages List DataMenuItemHow Used CallbackSaveas...Saves current List Master to adifferent F IG-filelmsaveasQuitExits List Master, with opt
15 Examples of GUIs Created ProgrammaticallyGUI. If the T ag has any other value, the program closes the figure anddisplays an error alert.The Quit me
A GUI That Manages List Databuttons that migrate items higher or lower in the list box. It disables the MoveUp button when the selected item is at the
About the Simple Programmatic GUI ExampleThe next topic, “Functions for the Simple Programmatic GUI” on page 3-3,summarizes the functions used to crea
15 Examples of GUIs Created ProgrammaticallyCalled from a blank GUI, the function requests a name, and then populatesthe figure with all controls. Cal
A GUI That Manages List DataList Master List CallbacksThe six callbacks not associated with m enu items are listed and describedbelow. Click any callb
15 Examples of GUIs Created Programmatically% Get the f igur e handle and from that, the listbo x handlefh = ancestor(hObject,'figure') ;lh
A GUI That Manages List DataUtility Function How Us e disguidirtyReturns logical state of the figure’s dirty flagmake_list_output_nameConverts the nam
15 Examples of GUIs Created ProgrammaticallyNote Use application data to communicate information betw een uicontrolsand other objects in GUIs you crea
Color PaletteColor PaletteIn this section...“About the Color Palette Example” on page 15-51“Techniques Used in the Color Palette Example” on page 15-5
15 Examples of GUIs Created ProgrammaticallyThe colorPalette function populates a GUI figure or panel with a colorpalette. See “View and Run the C olo
Color Palette• A More Colors push button• A preview of the selected c olor, below the color cells, defined as a textcomponent• Text components to spec
15 Examples of GUIs Created ProgrammaticallyCall the colorPalette FunctionYou can call thecolorPalette function with a statement such asmGetColorFcn =
Color PaletteTechniques Usedin the Color Palette ExampleThis example illustrates the following techniques:• Retrieving output from the GUI when it ret
3 How to Create a Simple GUI ProgrammaticallyMATLAB Functions Used to Create the Simple Programmatic GUI(Continued)Function DescriptionmoveguiMove GUI
15 Examples of GUIs Created Programmatically3 Click here to display the GUI code file in the Editor (read-only).Note Do n o t save GUI files to the ex
Color PaletteThe example also includes the helper functions listed in the following table.Function DescriptionlayoutComponentDynamically creates the E
15 Examples of GUIs Created Programmatically7 Callback definitions. These callbacks, which service the GUI components,are subfunctions of thecolorPale
Color PaletteThe colorPalette function then defines the valid custom properties in a3-by-3 cell array.mPropertyDefs = {... % The supported custom prop
15 Examples of GUIs Created ProgrammaticallyPass Output to a Caller on ReturningIf a host GUI calls the colorPalette function with an output argument,
Color PaletteJust before returning, colorPalette assigns mOutputArgs the functionhandle for itsgetSelectedColor helper function and then assignsmOutpu
15 Examples of GUIs Created Programmaticallyy = ceil(pt(1,2));color = mGetColorFcn();% update color of the selecte d blockmIconCData(y, x,:) = color;l
Icon EditorIcon EditorIn this section...“About the Icon Editor Example” on p age 15-63“View and Run the Icon Editor Code” on page 15-65“Subfunction Su
15 Examples of GUIs Created ProgrammaticallyIcon Editor GUI ComponentsThe GUIincludes the following components:• An edit text box that instructs the u
Icon Editor• A pane l, configured as a line , that separates the icon editor from the OKand Cancel buttons.• An OK push button that causes the GUI to
Create the Simple Programmatic GUI Code FileCreate the Simple Programmatic GUI Code FileStart by creating a file for the example GUI. Because the file
15 Examples of GUIs Created ProgrammaticallyPDF, go to the corresponding section in the MATL AB Help Browser to usethe links.If you intend to modify t
Icon EditorNote Do n o t save GUI files to the examples folder where you fo und them,or you will overwrite the original files. Save them to your curre
15 Examples of GUIs Created ProgrammaticallySubfunction SummaryThe icon editor e xample includes the callbacks listed in the following table.Function
Icon EditorFunction DescriptionlocalEditColorChanges the color of an icondata point to the currentlyselected color. Call the functionmGetColorFcn retu
15 Examples of GUIs Created ProgrammaticallyCode File OrganizationThe iconEditor is programmed using nested functions. Its code is organized inthe fol
Icon Editor• “Retrieve Output o n R eturn from a GUI” on page 15-73• “Protect a GUI from Inadvertent Access” on p age 15-74• “Run a GUI on Multiple Pl
15 Examples of GUIs Created ProgrammaticallyWhen the user clicks the Cancel button, its callback,hOCancelButtonCallback, effectively deletes the icon
Icon EditormIconWidth = 16; % Use input property ' iconwidth' to initializemIconHeight = 16; % Use input property 'ic onheight' to
15 Examples of GUIs Created ProgrammaticallymOutputArgs{} = mIco nCData;if nargout>0[varargout{1:nargout}] = mOutputAr gs{:};endThis code is the la
Icon EditorRun a GUI on Multiple PlatformsThe prepareLayout utility function s ets various properties of all the GUIcomponents to enable the GUI to re
3 How to Create a Simple GUI ProgrammaticallyThe next section, “Lay Out the Simple Programmatic GUI” on page 3-7, showsyou how to add components to yo
15 Examples of GUIs Created ProgrammaticallySelect Units. The prepareL ayou t function decides what units to use basedon the G UI’s resizability. It u
Icon EditorShare Data Between Two GUIsThe iconEditor embeds a GUI, the colorPalette, to enable the user to selectcolors for the icon cells. The colorP
15 Examples of GUIs Created ProgrammaticallyThe iconEditor’s loca lEdi tColor helper function calls mGetColorFcn,the function returned bycolorPalette,
Icon Editorif strcmpi(get( topC ontainer, 'Resize') ,'on ')set(allObjects(isprop(allObjects,'Unit s')),...'Units&ap
15 Examples of GUIs Created Programmatically15-80
AExamplesUse th i s list to find examples in the documen ta t ion.
A ExamplesSimple Examples (GUIDE)“About the SimpleGUIDEGUIExample”onpage2-9“Use a Modal Dialog Box to Confirm an Operation (GUIDE)” on page 10-98“Time
Simple Examples (Programmatic)Simple Examples (Programmatic)“About the S imple Programmatic GUI Example” on page 3-2A-3
A ExamplesApplication Examples (GUIDE)“A Working GUI with Many Components” on page 6-23“GUI with M ultiple Axes (GUIDE)” on page 10-2“GUI for Animatin
Programming GUI Components (GUIDE)Programming GUI Components (GUIDE)“Push Button” onpage 8-30“Toggle B utton” on page 8-31“Radio Button” on page 8-32“
LayOuttheSimpleProgrammaticGUILayOuttheSimpleProgrammaticGUIIn this section...“Create a Figure for a Programmatic GUI” on page 3-7“Add C omponents to
A ExamplesApplication-Defined Data (GUIDE)“Sharing Data with UserData” on page 9-11“Sharing Data with Application D ata” on page 9-14“Sharing Data wit
GUI Layout (Programmatic)GUI Layout (Programmatic)“File Template”on page 11-4“Check Box” on page 11-15“Edit Text” on page 11-17“ListBox”onpage 11-20“P
A ExamplesProgramming GUI Components (Programmatic)“Check Box” on page 12-21“Edit Text” on page 12-21“List B ox” on page 12-23“Pop-Up Menu”on page 12-
Application-Defined Data (Programmatic)Application-Defined Data (Programmatic)“Nested Functions Example: Passing Data Between Components” onpage 13-11
A ExamplesApplication Examples (Programmatic)“GUI with Axes, Menu, and Toolbar” on page 15-4“GUI that Displays and Graphs Tabular Data” on page 15-19“
IndexIndexAActiveX controlsadding to GUI layout 6-77programming 8-49 12-34aligning componentsin GUIDE 6-89Alignment Objects ToolGUIDE 6-89application
Indexcontext menusassociating with an object 6-120creating in GUIDE 6-101creating with GUIDE 6-114menu items 6-116parent menu 6-114cross-platform comp
Indexlistmaster 15-33tableplot 15-19GUI exportconfirmation 5-2GUI FIG-filesopening 10-60GUI filesin GU IDE 7-2GUI initializationcontrolling for single
Indexinterrupting callbackexample of 10-22LLayout Editorshow component names 5-7Layout Editor windowshow file extension 5-7show file path 5-7list boxe
Indexcreating in GUIDE 6-114singleton GUIdefined 5-13GUIDE option 5-12size of GUIsetting w ith GUIDE 6-15sliders 6-21 11-12status barshow in GUIDE Lay
3 How to Create a Simple GUI Programmaticallyhcontour = uicontrol('Style','p ushbutton',...'String','Countour'
LayOuttheSimpleProgrammaticGUI4 Align all components except the axes along their centers with the followingstatement. Add it to the code file followin
3 How to Create a Simple GUI Programmatically7 Run your code by typing simple_gui2 at the command line. This is whatyour GUI now looks like. Note that
CodetheSimpleProgrammaticGUICode the Simple Programmatic GUIIn this section...“Program the Pop-Up Menu” on page 3-11“Program the Push Buttons” on page
Select a GUI Template ... 6-6Access the Templates... 6-6Template Descriptions...
3 How to Create a Simple GUI ProgrammaticallyendThe next topic, “Program the Push Buttons” on page 3-12, shows you how towrite callbacks for the three
CodetheSimpleProgrammaticGUIthat particular event. But how does the software know which callback toexecute? You must use each component’sCallback prop
3 How to Create a Simple GUI Programmaticallyresize when the GUI is resized. Normalized units map the lower-left cornerofthefigurewindowto(0,0) and th
CodetheSimpleProgrammaticGUIfunction simple _gui 2% SIMPLE_GUI 2 Select a data set from the pop-u p menu, then% click one of the plot-typ e push butto
3 How to Create a Simple GUI Programmaticallyset(f,'Name','Simple GUI')% Move the GUI to the center of the sc reen .movegui(f,&apo
CodetheSimpleProgrammaticGUI% Create and then hide the GUI as it is being constructed.f = figure('Visible','off','Pos ition&a
3 How to Create a Simple GUI Programmaticallyset(f,'Name','Simple GUI')% Move the GUI to the center of the sc reen .movegui(f,&apo
CodetheSimpleProgrammaticGUIfunction con tour button_Callback(source, eventdata)% Display contour plot of the currently se lected data.contour(current
3 How to Create a Simple GUI ProgrammaticallyUse the Completed Simple Programmatic GUIOpen and Run the GUI1 Run the GUI by typing the name of the code
UsetheCompletedSimpleProgrammaticGUI3 Try other combinations before closing the GUI.3-21
Standard Background C olor ... 6-138Cross-Platform Compatible Units... 6-139Save and Run a GUIDE GUI7Name a GUI
3 How to Create a Simple GUI Programmatically3-22
Create GUIs with GUIDEChapter 4, What Is GUIDE?(p. 4-1)Introduces GUIDEChapter 5, G UIDE Preferencesand Options (p. 5-1)Describes briefly the availabl
4What Is GUIDE?• “GUIDE : Getting Started” on page 4-2• “GUIDE Tools Summary” on page 4-3
4 What Is GUIDE?GUIDE: Getting StartedIn this section...“GUI Layout” on page 4-2“GUI Programming” on page 4-2GUI LayoutGUIDE, the MATLAB graphical use
GUIDE Tools SummaryGUIDE Tools Summar yThe GUIDE tools are available from the Layout Editor shown in the figurebelow. The tools are called out in the
4 What Is GUIDE?Use ThisTool... To...LayoutEditorSelect components from the component palette, at the leftside of the Layout Editor, and arrange them
GUIDE Tools SummaryUse ThisTool... To...EditorDisplay, in your default editor, the code file associated withthe GUI. See “Files Generated by GUIDE” o
4 What Is GUIDE?4-6
5GUIDE Preferences andOptions• “GUIDE Preferences” on page 5-2• “GUI Options” on page 5-9
Komentarze do niniejszej Instrukcji