Creating Graphical User Interfaces - Matlab

download Creating Graphical User Interfaces - Matlab

of 180

Transcript of Creating Graphical User Interfaces - Matlab

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    1/180

    Computation

    Visualization

    Programming

    Creat ing Graphical User InterfacesVersion 1

    MATLAB®

    The Language of Technical Computing

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    2/180

    How to Contact The MathWorks:

    www.mathworks.com Web

    comp.soft-sys.matlab Newsgroup

    [email protected]  Techn ical support

    [email protected]  Product enh ancement [email protected]  Bug reports

    [email protected]  Docum enta tion error reports

    [email protected]  Order stat us, license renewals, passcodes

    [email protected]  Sales, pricing, an d general informa tion

    508-647-7000 Phone

    508-647-7001 Fax

    The MathWorks, Inc. Mail

    3 Apple Hill Drive

    Na tick, MA 01760-2098

    For cont act informat ion about worldwide offices, see the Mat hWorks Web site.

    Creating Graph ical User Interfaces 

     ©  COPYRIGHT 2000 by The Math Works, Inc.

    The softwar e described in this documen t is furnished under a license agreemen t. The softwar e may be usedor copied only under the t erms of the license agreemen t. No part of this m anu al ma y be photocopied or r epro-duced in any form with out prior written consent from The MathWorks, Inc.

    FEDERAL ACQUISITION: This provision applies to all acquisitions of the Pr ogram and Documen tat ion byor for th e federal governmen t of the United Sta tes. By accepting delivery of the P rogram, th e governmenthereby agrees tha t t his softwar e qualifies as "commercial" comput er software with in th e mean ing of FARPar t 12.212, DFARS Pa rt 227.7202-1, DFARS Pa rt 227.7202-3, DFARS Pa rt 252.227-7013, and DFARS Part252.227-7014. The term s and conditions of The Math Works, Inc. Softwar e License Agreement sh all perta into the governm ent’s use a nd disclosure of the P rogram a nd Documen tat ion, and sh all supers ede anyconflicting contr actua l term s or conditions. If this license fails to meet the government ’s minimu m needs oris inconsisten t in any respect with federal procurement law, the governmen t agrees to retur n the Pr ogra mand Document at ion, unused, to Math Works.

    MATLAB, Simulink, Stateflow, Handle Graph ics, and Rea l-Time Workshop ar e registered tr adema rks, an dTarget Lan guage Compiler is a tr adema rk of The Math Works, Inc.

    Other product or bran d names are t rademarks or registered tr ademarks of their respective holders.

    Print ing History: November 2000 New for MATLAB 6.0 (Release12) (Online only)

    June 2001 R ev ised for M ATLAB 6.1 (R ele ase 12.1 (On line on ly)

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    3/180

    i

    Contents

    1

    Getting S tarted w ith GUIDE

    GUIDE – GUI Deve lopmen t Environme nt   . . . . . . . . . . . . . . . 1-3

    GUIDE Toolset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4

    Un ders ta ndin g How to Crea te GUI s . . . . . . . . . . . . . . . . . . . . . 1-4

    Getting Started Example   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5

    Exa mple – Th e GUI Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5

    Exa mple – La ying Out t he GU I . . . . . . . . . . . . . . . . . . . . . . . . . 1-6

    Cr ea tin g th e Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7

    Exa mple – P rogra mm ing th e GUI . . . . . . . . . . . . . . . . . . . . . . 1-16

    Exa mple – Test ing th e GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-19

    Exa mple – Adding th e File Menu t o th e GUI . . . . . . . . . . . . . 1-20

    Exam ple – Program ming the Menu Callbacks . . . . . . . . . . . . 1-24

    User Interface Controls   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-26

    Pu sh Bu tt ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-26

    Toggle But tons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-27

    Ra dio But ton s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-27

    Checkboxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-29

    Ed it Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-29

    St at ic Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-30

    Slider s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-30

    Fr am es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-32

    List Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-33

    Popu p Men us . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-34

    En abling or Disablin g Cont rols . . . . . . . . . . . . . . . . . . . . . . . . 1-35

    Axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-36Figu re . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-37

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    4/180

    i i

    2

    MATLAB GU Is

    Introduction   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2

    Creating GUIs with GUIDE   . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3

    GUI Developmen t E nvironm ent . . . . . . . . . . . . . . . . . . . . . . . . . 2-3

    Edit ing Version 5 GUIs with Version 6 GUIDE   . . . . . . . . . . . 2-6

    Select in g GUIDE Application Options  . . . . . . . . . . . . . . . . . . . 2-8

    Configur ing t he App lication M-F ile . . . . . . . . . . . . . . . . . . . . . . 2-8

    Resize Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10

    Mak ing Your GUI N onresizable . . . . . . . . . . . . . . . . . . . . . . . . 2-10

    Allowing Proportional GUI Resizing . . . . . . . . . . . . . . . . . . . . . 2-10

    Us er-Sp ecified Res ize Oper at ion . . . . . . . . . . . . . . . . . . . . . . . . 2-11

    Comman d-Line Acces sibi l i ty  . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12

    Access Opt ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12Figur e Pr operties Th at Contr ol Access . . . . . . . . . . . . . . . . . . . 2-12

    Us ing findobj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-13

    Electing to Generate Only the FIG-File  . . . . . . . . . . . . . . . . . 2-14

    The Generated M-File   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15

    Callback F un ction N am es an d Argum ent s . . . . . . . . . . . . . . . . 2-15

    Applicat ion Allows On ly One In sta nce to Run . . . . . . . . . . . . . 2-18

    Usin g the S ystem Backgroun d Colors . . . . . . . . . . . . . . . . . . . 2-18

    Wait ing for User In pu t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20

    Renaming Applicat ion Fi les and Tags   . . . . . . . . . . . . . . . . . . 2-21

    Us ing Save As . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-21

    Gett ing Ever yth ing Right . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-21

    Cha nging Componen t Ta g Pr operties . . . . . . . . . . . . . . . . . . . . 2-21

    Cha nging t he N am e of Callback Su bfunctions . . . . . . . . . . . . . 2-22

    Cha nging th e Nam e of th e M-File an d FIG-File . . . . . . . . . . . 2-24

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    5/180

    i i i

    3

    GUIDE Layou t Tools

    GUI Layout Tools   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2

    Laying Out GUIs – The Layou t Editor   . . . . . . . . . . . . . . . . . . . 3-4

    Pla cing an Object I n t he La yout Area . . . . . . . . . . . . . . . . . . . . . 3-4

    Activa tin g th e Figu re . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5

    Sa ving t he Layou t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6

    Displa ying Your GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6

    Layout Edit or Pr eferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6

    Layout Edit or Context Menu s . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7

    Aligning Components in the Layout Edi tor  . . . . . . . . . . . . . 3-10

    Aligning Group s of Component s – The Alignmen t Tool . . . . . 3-10

    Gr ids a nd Ru lers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-12

    Aligning Componen ts t o Guide Lines . . . . . . . . . . . . . . . . . . . . 3-13

    Fr ont t o Back P ositionin g . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-14

    Set t ing Component Propert ies – The Property Inspector  3-16

    Viewing the Object Hierarchy – The Object Brow ser   . . . . 3-18

    Creating Menus – The Menu Editor   . . . . . . . . . . . . . . . . . . . . 3-19

    Definin g Menu s for t he Men uba r . . . . . . . . . . . . . . . . . . . . . . . 3-19

    Menu Callba cks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-24

    Definin g Cont ext Men us . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-25

    Saving the GUI  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-29

    FI G-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-29

    4

    Programming GUIs

    GUI Programm ing Topics   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2

    Unde rstanding th e Application M-File   . . . . . . . . . . . . . . . . . . 4-3

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    6/180

    iv

    Execut ion P at hs in t he Applicat ion M-File . . . . . . . . . . . . . . . . 4-4

    In itia lizing th e GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7

    Managing GUI Data w i th the Handles Structure  . . . . . . . . 4-10

    Pa ssing Data in t he Ha ndles Stru cture . . . . . . . . . . . . . . . . . . 4-10

    Obtaining th e Updat ed Han dles Structur e . . . . . . . . . . . . . . . 4-12

    If You Are Not U sing a Ha ndles S tr uctu re . . . . . . . . . . . . . . . . 4-12

    Applicat ion-Defined Da ta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14

    Desig ning for Cross-Platform Compa tibi l i ty   . . . . . . . . . . . . 4-15

    Usin g the Default S ystem Font . . . . . . . . . . . . . . . . . . . . . . . . . 4-15

    Usin g Sta nda rd Ba ckground Color . . . . . . . . . . . . . . . . . . . . . . 4-16

    Cross-Plat form Compat ible Figure U nit s . . . . . . . . . . . . . . . . . 4-17

    Types of Cal lbacks   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-18

    Callback P ropert ies for All Grap hics Objects . . . . . . . . . . . . . . 4-18

    Callback P ropert ies for F igures . . . . . . . . . . . . . . . . . . . . . . . . 4-18

    Which Ca llback E xecut es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-19

    Adding A Callba ck . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-19

    Interrupting Executing Callbacks   . . . . . . . . . . . . . . . . . . . . . 4-20

    Contr olling Int err upt ibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-20

    The Even t Qu eue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-20

    Even t P rocessing Durin g Callback Execution . . . . . . . . . . . . . 4-21

    Control l ing GUI Figure Window Beh avior   . . . . . . . . . . . . . . 4-23

    Us ing Moda l Figu re Win dows . . . . . . . . . . . . . . . . . . . . . . . . . . 4-23

    5Appl icat ion Exam ples

    Examples of Application Techniques  . . . . . . . . . . . . . . . . . . . . 5-2

    GUI with Mult iple Axes   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3

    Techniqu es Used in th e Exa mple . . . . . . . . . . . . . . . . . . . . . . . . 5-3

    View th e Layout an d Applicat ion M-File . . . . . . . . . . . . . . . . . . 5-4

    Design of th e GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    7/180

    v

    Plot P ush But ton Ca llback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7

    Launch ing a Dialog to Confirm an Operation   . . . . . . . . . . . . 5-9

    Dialog Requ irem en ts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9

    View th e Layout an d Applicat ion M-File . . . . . . . . . . . . . . . . . 5-10

    Imp lement ing th e GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10

    The Close But ton C allba ck . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-12

    The Confirm a tion Dia log M-file . . . . . . . . . . . . . . . . . . . . . . . . 5-12Laun ch t he Dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-13

    Specify th e Location of th e Dia log . . . . . . . . . . . . . . . . . . . . . . . 5-14

    Wait for U ser Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-14

    Execut ing a Ca llback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15

    Definin g the Yes and N o But tons Ca llbacks . . . . . . . . . . . . . . 5-15

    Pr otecting the GU I with a Close Request F un ction . . . . . . . . . 5-16

    List Box Directory Reade r   . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-18

    View th e Layout an d Applicat ion M-File . . . . . . . . . . . . . . . . . 5-18

    Imp lement ing th e GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-19

    Specifying the Directory to List . . . . . . . . . . . . . . . . . . . . . . . . . 5-19

    Loadin g th e List Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-21The List Box Callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-22

    Accessing Workspace Variables from a List Box  . . . . . . . . . 5-24

    Techniqu es Used in This E xam ple . . . . . . . . . . . . . . . . . . . . . . 5-24

    View th e Layout an d Applicat ion M-File . . . . . . . . . . . . . . . . . 5-25

    Rea ding Works pa ce Va ria bles . . . . . . . . . . . . . . . . . . . . . . . . . . 5-25

    Readin g th e Selections from t he List Box . . . . . . . . . . . . . . . . . 5-26

    A GUI to Set Simulink Model Param eters   . . . . . . . . . . . . . . 5-28

    Techniqu es Used in This E xam ple . . . . . . . . . . . . . . . . . . . . . . 5-28

    View th e Layout an d Applicat ion M-File . . . . . . . . . . . . . . . . . 5-28

    How t o Use t he GUI (Text of GUI H elp) . . . . . . . . . . . . . . . . . . 5-29

    Laun ching t he G UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-30

    Pr ogram ming th e Slider a nd E dit Text Component s . . . . . . . . 5-31

    Run nin g th e Simu lat ion from th e GUI . . . . . . . . . . . . . . . . . . . 5-33

    Removing Results from the List Box . . . . . . . . . . . . . . . . . . . . 5-34

    Plottin g th e Results Dat a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-35

    The GUI H elp Bu tt on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-37

    Closing t he GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-38

    The List Box Callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-38

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    8/180

    vi Contents

    An Address Book Reader   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-40

    Techniqu es Used in This E xam ple . . . . . . . . . . . . . . . . . . . . . . 5-40

    Man agin g Global Da ta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-40

    View th e Layout an d Applicat ion M-File . . . . . . . . . . . . . . . . . 5-41

    Laun ching t he G UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-41

    Loading a n Addr ess Book In to th e Reader . . . . . . . . . . . . . . . . 5-43

    The Cont act N am e Callback . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-45

    The Cont act P hone # Ca llback . . . . . . . . . . . . . . . . . . . . . . . . . 5-47Pa ging Thr ough th e Address Book – Prev/Next . . . . . . . . . . . . 5-48

    Saving Chan ges to the Address Book from th e Menu . . . . . . . 5-50

    The Cr ea te N ew Men u . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-51

    The Addr ess Book Resize Fu nction . . . . . . . . . . . . . . . . . . . . . . 5-52

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    9/180

     

    1

    Gett ing Sta rt ed with

    GUIDE

    GUIDE – GUI Deve lopmen t Environme nt . . . . . . . 1-3

    GUIDE Toolset . . . . . . . . . . . . . . . . . . . 1-4

    Und ersta nding How to Creat e GUIs . . . . . . . . . . . 1-4

    Getting Started Example   . . . . . . . . . . . . . . 1-5

    Exam ple – The GUI Design . . . . . . . . . . . . . . 1-5

    Exam ple – Laying Out th e GUI . . . . . . . . . . . . . 1-6

    Creat ing th e Layout . . . . . . . . . . . . . . . . . 1-7

    Exam ple – Program ming the GUI . . . . . . . . . . . . 1-16

    Exam ple – Testing the GUI . . . . . . . . . . . . . . 1-19

    Exam ple – Adding th e File Menu to th e GUI . . . . . . . 1-20Exam ple – Program ming the Menu Callbacks . . . . . . . 1-24

    User Interface Controls . . . . . . . . . . . . . . . 1-26

    Pu sh Butt ons . . . . . . . . . . . . . . . . . . . . 1-26

    Toggle But tons . . . . . . . . . . . . . . . . . . . 1-27

    Radio Bu tt ons . . . . . . . . . . . . . . . . . . . . 1-27

    Checkboxes . . . . . . . . . . . . . . . . . . . . . 1-29

    Ed it Text . . . . . . . . . . . . . . . . . . . . . . 1-29

    St at ic Text . . . . . . . . . . . . . . . . . . . . . 1-30

    Sliders . . . . . . . . . . . . . . . . . . . . . . . 1-30

    Fra mes . . . . . . . . . . . . . . . . . . . . . . 1-32

    List Boxes . . . . . . . . . . . . . . . . . . . . . 1-33

    Popup Menus . . . . . . . . . . . . . . . . . . . . 1-34En abling or Disabling Contr ols . . . . . . . . . . . . . 1-35

    Axes . . . . . . . . . . . . . . . . . . . . . . . . 1-36

    Fig ure . . . . . . . . . . . . . . . . . . . . . . 1-37

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    10/180

    1 Getting Started with GUIDE

    1-2

    This section illustra tes t he pr ocess of using GUIDE to creat e GUIs:

    • GUI Development Environment – overview of the layout tools provided by

    GUIDE.

    • Getting Sta rted E xample – an example illust ra ting how to use GUIDE.

    • User Int erface Controls – descriptions of the components you use to create

    GUIs.

    For more in depth informa tion a bout creating graph ical user s interfaces see

    MATLAB GU Is.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    11/180

    GUIDE – GUI Development Environment

    1-3

    GUIDE – GUI Development Environment

    GUIDE, MATLAB’s Gr aph ical User Int erface development environm ent,

    provides a set of tools for laying out your GU I. The La yout Edit or is the contr ol

    pan el for GUIDE. To sta rt t he Layout Editor, use th e guide comma nd.

    The following pictu re sh ows t he La yout Editor with the Show names in

    component palet te  preference selected.

    Component

    Palette

    Alignm ent Tool Menu Editor Pr operty In spector Figure ActivatorObject Browser

    Layout Area

    Figure Resize Tab

    Undo

    Redo

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    12/180

    1 Getting Started with GUIDE

    1-4

    GUIDE ToolsetThe following link s provide more inform at ion on t he full set of GUIDE

    development tools.

    • Layout Editor – add a nd a rr an ge objects in the figur e window.

    • Alignmen t Tool – align objects wit h r espect to each oth er.

    • Pr opert y Inspector – inspect a nd set property values.

    • Object Browser – observe a hierarchical list of the Handle Graphics objects

    in th e curren t MATLAB session.

    • Menu E ditor – creat e menu s for th e window menu bar a nd context m enus for

    an y component in your layout .

    Understa nding How to Crea te GUIsFor more in depth informa tion on h ow GUIDE works, see Creating GUIs with

    GUIDE. For a simple example to get sta rt ed using GUIDE see th e next section,

    A GUI Example.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    13/180

    Getting Started Example

    1-5

    Getting Started Example

    This example shows how to create a GUI u sing GUIDE. It illust rat es the

    process you should follow when creating your GUI. This process entails:

    • Design t he GUI – often it is better to design t he GUI on paper beforebeginn ing the implement at ion pr ocess.

    • Laying out t he GUI figure – th e GUI figure is the window that cont ains th e

    user int erface controls, such as push butt ons and men us an d can a lso contain

    axes for displaying graph s an d images.

    • Pr ogram the GU I – th e M-file genera ted by GUIDE displays an d cont rols the

    GUI figure you created with GUIDE. It is in this M-file th at you pr ogra m th e

    callback functions for each user interface control.

    GUIDE’s layout tools enable you t o add an d ar ra nge components in th e GUI

    figure. When you activate or sa ve your GUI for t he first time, GUIDE generat es

    the M-file you u se to program th e GUI.

    This example is presented in five sections:

    • Designing t he GU I – a description of th e GUI design

    • Laying out the GU I – placing the cont rols within t he Layout E ditor

    • Pr ogram ming th e GUI – wr iting the callbacks for t he cont rols

    • Laying out t he men u – adding the menu to the GUI figure

    • Pr ogram ming th e menu callbacks – writing the callbacks for th e menus

    Ex a mple – The GUI DesignThe GUI used in th is examp le cont ains one axes tha t can display eith er a

    surface, mesh, or cont our plot of data selected from th e popup m enu. Th e File  

    menu provides options t o print t he gra phic and t o close th e GUI.

    The following pictu re sh ows a sketch similar t o what you might use a s a

    star ting point for the design.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    14/180

    1 Getting Started with GUIDE

    1-6

    The popup menu contains three strings – “peaks”, “membrane”, and “sinc”,

    which enable the user t o select th e data to plot. The GUI program gener at es

    th is data by executing one of three fun ctions.

    Ex a mp le – La ying O ut the GUIThis section illustrates how to layout GUI components (i.e., user interface

    cont rols, like push butt ons, popup menu s, text labels, etc.) in the GUI.

    Layout and Code for the Example

    Use t he following links t o display th e GUIDE Layout Editor a nd t he MATLAB

    Editor with a completed version of th is example. This enables you to see th e

    values of all component p roperties and t o un dersta nd h ow th e component s are

    as sembled t o crea te t he GU I. You can a lso see a complete listing of th e code

    that is discussed in the following sections.

    ) LOH

    Select Data

    peaks

    Contour

    Mesh

    Surf

    Axes

    Push buttons toselect plot type

    Popup for selectingdata

    File menu withPrint and Close

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    15/180

    Getting Started Example

    1-7

    Note The following links execute MATLAB commands and are designed towork within th e MATLAB Help browser. The first link ad ds a directory to your

    MATLAB path.

    Layout Editor with completed GUI layout

    MATLAB Ed itor with complet ed a pplication M-file

    View an Animated Demo

    The following link displays an an imated version of th is example.

    Show GUIDE dem onst ra tion

    Creating the LayoutOpen the La yout Editor u sing the guide comma nd. This displays a blank

    layout grid to which you can added component s t ha t you select from th epalette.

    1. Set the GUI Figure Size

    Specify th e size of the GU I by resizing the grid ar ea in th e Layout E ditor. Click

    on th e lower-right corn er a nd resize the grid u ntil it is a bout 4-by-3 inches.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    16/180

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    17/180

    Getting Started Example

    1-9

    2. Add the Components

    Select th e component s to add from the pa lette an d drag th em into the layout

    area . You can r esize components from a ny corn er h an dle while it is selected.

    Add thr ee push butt ons, a st atic text, a popup menu, an d an axes. Arran gethem as shown in t he following pictur e.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    18/180

    1 Getting Started with GUIDE

    1-10

    3. Align the Objects

    To align component s with respect to one an other, select Align Objects  from th e

    Tools  men u. The Alignment Tool sets t he r elative vertical and h orizont al

    alignment of selected component s. The following pictu re sh ow the t hree push

    butt ons selected (ctrl+click t o multiple select) and r eady t o be aligned

    according to the set tings:

    • 20 pixels spacing between pu sh bu ttons in the vertical direction.

    • Left-aligned in the horizontal direction.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    19/180

    Getting Started Example

    1-11

    4. Set Properties for Each Component

    To set the properties of each component, select the Property Inspector from

    the View  menu.

    Push Buttons and Static Text

    Set the String properties of the pu sh but tons an d sta tic text to creat e the

    labels. For example, the following picture shows the Surf   push button

    properties.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    20/180

    1 Getting Started with GUIDE

    1-12

    Popup Menu Items

    Ea ch item in th e popup men u list needs to be on a sepa ra te line in th e String 

    property edit box:

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    21/180

    Getting Started Example

    1-13

    Tag and Callback Properties

    When you first a dd a component to the layout, its Callback property is set t o

    the string .

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    22/180

    1 Getting Started with GUIDE

    1-14

    When you save or activate th e GUI, GUIDE converts t his string to one th atcalls th e callback subfunction in th e generat ed M-file. GUIDE u ses th e

    component’s Tag pr operty to na me its callback function. It is, therefore, useful

    to set Tag properties t o descriptive nam es before you sa ve or activate th e GUI

    for t he first time.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    23/180

    Getting Started Example

    1-15

    This examp le sets th e popup men u Tag t o data_popup, resulting in th e nam e

    data_popup_Callback for t he popup menu ’s callback function. Set the push

    butt on Tags to surf_pushbutton, mesh_pushbutton, and contour_pushbutton.

    The next section, E xample – Pr ogra mming t he GUI, pr ovides more informat ion

    on the callback functions for this GUI.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    24/180

    1 Getting Started with GUIDE

    1-16

    5. Activate the GUI

    Activat e the GUI by selectin g Activate Figure  from th e Tools  menu or use the

    activator but ton from th e GUIDE toolbar. The following pictur e shows th e

    GUI. See Activating t he F igur e for m ore detailed informa tion on wha t figur e

    activation does.

    The Application M-File

    Activating t he GUI a lso opens the MATLAB editor with th e M-file genera ted

    for t he GUI. You m ust program t he various components in your GUI in th is

    M-file. The next section show how to do th is.

    Note The na me of the F IG-file saved by the Layout Edit or a nd th e generat edapplication M-file must match. See Renaming Application Files and Tags if

    you wan t t o renam e files or cha nge Tags after first a ctivating th e GUI.

    Example – Programming the GUIWhen you first sa ve or a ctivate th e GUI, GUIDE genera tes th e application

    M-file that will cont ain a ll the code to laun ch an d contr ol th e GUI. You m ust

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    25/180

    Getting Started Example

    1-17

    write the callbacks – th e fun ctions that execute when u sers activate a

    component in th e GUI.

    The app licat ion M-file:

    • Initializes and lau nches the GUI.

    • Cont ains t he callback functions for a ll component s in t he GUI.

    GUIDE genera tes th is M-file with empty su bfun ctions for each component th at

    ha s a callback associated with it – in this example, the th ree push bu ttons an d

    the popup men u ha ve callbacks.

    A Note About Handles and Global Data

    A key featu re in t he genera ted M-file is th e handles stru cture. This structure

    ha s two purposes. It:

    • Stores the h an dles of all controls, menu s, and a xes used in the GU I.

    • Stores global data used in th e progra m.

    Accessing Handles. Each object handle is stored in a field of the handles 

    stru cture ha ving th e same na me as t he object’s Tag. For example,

    handles.data_popup

    cont ains th e han dle of the popup m enu u sed in this example.

    Storing Global Data. You can store data an d pass it to any callback using the

    handles str uctur e. To do this, creat e a n ew field in th e handles structure and

    save it using the guidata function. For exa mple, from th e callback of th e object

    whose han dle is h,

    handles.x_data = X;

    guidata(h,handles)

    saves the variable X in the x_data field of th e handles stru cture. guidata then

    writes t he n ew version of handles to the figure’s app licat ion dat a t o save it. To

    obtain X in another callback, reference the correct field:

    X = handles.x_data;

    For more deta iled informa tion on t he handles structure, see:

    • Creating and Storing the Handles Structure

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    26/180

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    27/180

    Getting Started Example

    1-19

    data_popup_Callback(handles.data_popup,[],handles)

    Push Button Callbacks

    Ea ch of the pu sh bu tt ons creat es a different type of plot u sing th e dat a specified

    by the curren t selection in the popup men u. Their callbacks get data from t hehandles structure an d then plot i t .

    Surf   push bu tton callback:

    function varargout = surf_pushbutton_Callback(h,eventdata,handles,varargin)

    z = handles.data; % Load data from handles structure

    surf(z);

    Mesh push butt on callback:

    function varargout = mesh_pushbutton_Callback(h,eventdata,handles,varargin)

    z = handles.data; % Load data from handles structure

    mesh(z)

    Contour push bu tt on callback:

    function varargout =

    contour_pushbutton_Callback(h,eventdata,handles,varargin)

    z = handles.data; % Load data from handles structure

    contour(z)

    Ex a mple – Testing the GUIAfter wr iting the callbacks, you can activate th e GUI to test it. Activate t he

    GUI by selecting Activate Figure  from th e Tools  menu or use th e activat or

    butt on from th e GUIDE toolbar. Select membrane in the popup menu and press

    the Contour push butt on. The GUI should look like this:

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    28/180

    1 Getting Started with GUIDE

    1-20

    Ex a mp le – Add ing the File M enu to the GUIThe GUI has a File  menu with t wo menu items:

    • Print – sends th e plot t o the user ’s default prin ter. This item is grayed out if

    th ere is no plot curr ently displayed.

    • Close  – closes the GU I window.

    To creat e the m enu, display the Menu Editor by selecting the Menu Editor 

    i tem in the Tool  menu.

    1. Add the File MenuUse t he New Menu tool to add th e top-level menu.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    29/180

    Getting Started Example

    1-21

    2. Set the Label and Tag

    Set the Label property to the word File. This is the n am e of the menu as it

    appears on the GUI menu bar. Set the Tag property t o a descriptive nam e.GUIDE uses the Tag property t o name t he m enu callback fun ction (as well as

    the field in th e handles stru cture t hat conta ins the menu han dle).

    Initially, the Callback property is set t o . This means GUIDE

    au toma tically adds a callback fun ction to th e application M-file when you sa ve

    or a ctivate th e GUI.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    30/180

    1 Getting Started with GUIDE

    1-22

    3. Add the Items

    Select File and click t he N ew Menu Item tool. Each t ime you click N ew Menu

    Item, th e editor adds a n ew submenu t o the selected menu .

    4. Set the Labels and Tags for the Menu Items

    Set the Label and Tag properties for each men u item. GUIDE gener ates a

    callback for each m enu item as well.

    Save or a ctivate th e GUI to add the menu t o the menu bar and t o add the

    callbacks to th e application M-file. The n ext section shows you how to program

    the menu.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    31/180

    Getting Started Example

    1-23

    5. Activate the GUIAfter creating th e menu s with th e Menu E ditor, you can a ctivat e the GUI fromthe La yout Editor. This cau ses GUIDE to generate t he empty callback

    functions in th e app licat ion M-file, which you can now progra m. Select sinc in

    the popup men u a nd click on the Mesh  push butt on. The activat ed GUI looks

    like th is when you pull down t he File  menu.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    32/180

    1 Getting Started with GUIDE

    1-24

    Example – Programming the Menu CallbacksAfter a dding the File  menu to the layout (you cann ot see the m enu ba r in th e

    Layout Editor), edit the application M-file. It will contain empty callback

    functions for the File  menu as well as th e Print and Close  items.

    File Menu Callback

    By defau lt, when a user clicks on th e File  menu , MATLAB displays the men u

    item s. Therefore, the only pur pose of th e File  men u callback in t his example is

    to disable the Print menu item when ther e is no plot being displayed. You can

    accomplish t his by checking to see if th e axes Children property is empt y (in

    which case, th ere is nothing displayed in th e axes).

    The men u’s Enable property cont rols wheth er a pa rt icular item is active or

    inactive. The item is grayed out if Enable is set t o off.

    The callback u ses isempty to determine if the axes conta ins a plot an d enables

    or disables th e men u accordingly.

    function varargout = file_menu_Callback(h, eventdata, handles, varargin)

    if isempty(get(handles.axes1,'Children'))

    set(handles.print_submenu,'Enable','off')

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    33/180

    Getting Started Example

    1-25

    else

    set(handles.print_submenu,'Enable','on')

    end

    The Print Item Callback

    The callback for the Print  menu item uses the print comman d to print th e

    current plot on th e user’s default print er. The -f option specifies th e GUI

    figure. Since t he figur e’s Tag property is set t o f igure1, th e figure’s ha ndle is

    cont ained in th e figure1 field of th e handles structure.

    function varargout = print_submenu_Callback(h, eventdata, handles, varargin)

    print -f handles.figure1

    The Close Item Callback

    The callback for the Close  menu item uses the delete comm an d to close the

    GUI figure. S ince th e figur e’s Tag property is set t o f igure1, the figure’s ha nd le

    is contained in t he figure1 field of the handles structure.

    function varargout = close_submenu_Callback(h, eventdata, handles, varargin)

    delete(handles.figure1)

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    34/180

    1 Getting Started with GUIDE

    1-26

    User Interface Controls

    The Layout Ed itor component palette cont ains t he user interface controls that

    you can us e in your GUI. Thes e component s ar e MATLAB uicontr ol objects an d

    are programmable via their Callback properties. This section provides

    inform ation on t hese component s.

    Push ButtonsPu sh but tons generat e an action when pr essed (e.g., an OK but ton ma y close a

    dialog box and apply sett ings). When you click down on a push butt on, it

    appea rs depressed; when you release th e mouse, the butt on’s appear ance

    retu rns t o its nondepressed sta te; and its callback execut es on t he butt on up

    event.

    Properties to Set

    • String – set th is propert y to th e cha racter st ring you wan t displayed on t he

    push butt on.

    • Tag – GUIDE uses the Tag property to na me th e callback subfunction in t heap plicat ion M-file. Set Tag to a descript ive nam e (e.g., close_button) before

    activating the GUI.

    Programming the Callback

    When t he user clicks on th e push butt on, its callback executes. Push butt ons

    do not return a value or mainta in a stat e.

    Push Buttons Sliders

    Toggle But tons Fra mes

    Radio But tons Listboxes

    Checkboxes Popup Menus

    Edit Text Axes

    Stat ic Text Figures

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    35/180

    User Interface Controls

    1-27

    Toggle ButtonsToggle butt ons generat e a n action an d indicate a binary s ta te (e.g., on or off).

    When you click on a t oggle butt on, it a ppears d epressed an d rema ins depressed

    when you release t he m ouse button, at which point t he callback executes. A

    subsequent mouse click retu rn s th e toggle butt on to th e nondepressed stat ean d aga in executes its callback.

    Programming the Callback

    The callback routine needs to query the t oggle butt on to determine wha t sta te

    it is in. MATLAB sets the Value property equal to the Max property when the

    toggle butt on is depressed (Max is 1 by default ) and equa l to the Min property

    when t he t oggle butt on is not depressed (Min is 0 by default ).

    From the GUIDE Application M-File

    The following code illust ra tes h ow to progra m t he callback in the GUIDE

    application M-file.

    function varargout = togglebutton1_Callback(h,eventdata,handles,varargin)

    button_state = get(h,'Value');

    if button_state == get(h,'Max')

    % toggle button is pressed

    elseif button_state == get(h,'Min')

    % toggle button is not pressed

    end

    Adding an Image to a Push Button or Toggle Button

    Assign th e CData property a n m-by-n-by-3 ar ra y of RGB values tha t d efine a

    tru ecolor ima ge. For exam ple, the ar ra y a defines 16-by-128 tr uecolor ima ge

    using ra ndom values between 0 and 1 (genera ted by rand).

    a(:,:,1) = rand(16,128);

    a(:,:,2) = rand(16,128);

    a(:,:,3) = rand(16,128);

    set(h,'CData',a)

    Radio ButtonsRadio butt ons are similar t o checkboxes, but ar e intended t o be mu tu ally

    exclusive within a group of related radio buttons (i.e., only one button is in a

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    36/180

    1 Getting Started with GUIDE

    1-28

    selected st at e at any given time). To activate a rad io butt on, click the m ouse

    butt on on t he object. The display indicat es th e sta te of th e butt on.

    Implementing Mutually Exclusive Behavior

    Radio buttons h ave two stat es – selected a nd n ot selected. You can query a ndset th e stat e of a ra dio butt on through its Value property:

    • Value = Max, button is selected.

    • Value = Min, butt on is not selected.

    To make r adio buttons m utu ally exclusive with in a group, the callback for ea ch

    radio butt on mu st set the Value property t o 0 on all other ra dio butt ons in the

    group. MATLAB sets th e Value property t o 1 on th e ra dio butt on clicked by th e

    user.

    The following su bfunction, when ad ded t o the a pplicat ion M-file, can be called

    by each ra dio butt on callback. The argum ent is an ar ra y containing th e

    ha ndles of all other radio buttons in th e group t ha t mu st be deselected.

    function mutual_exclude(off)

    set(off,'Value',0)

    Obtaining the Radio Button Handles. The ha ndles of the rad io butt ons are a vailable

    from th e handles str uctur e, which cont ains t he h an dles of all component s in

    th e GUI. This stru ctu re is an input a rgumen t to all ra dio butt on callbacks.

    The following code shows t he call to mutual_exclude being made from the first

    ra dio but ton’s callback in a group of four ra dio but tons.

    function varargout = radiobutton1_Callback(h,eventdata,handles,varargin)

    off = [handles.radiobutton2,handles.radiobutton3,handles.radiobutton4];

    mutual_exclude(off)

    % Continue with callback.

    .

    .

    After set ting the r adio butt ons to th e appropriate st ate, th e callback can

    cont inue with its implement at ion-specific tasks.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    37/180

    User Interface Controls

    1-29

    CheckboxesCheck boxes genera te an action wh en clicked an d indicate t heir sta te as

    checked or n ot checked. Check boxes are u seful when providing th e user with

    a n umber of independent choices th at set a mode (e.g., display a t oolbar or

    generate callback function prototypes).The Value property indicat es th e sta te of th e check box by ta king on the value

    of th e Max or Min property (1 and 0 respectively by default):

    • Value = Max, box is checked.

    • Value = Min, box is n ot checked.

    You can deter mine t he curr ent sta te of a check box from within its callback by

    querying the st at e of its Value property, as illust rat ed in t he following

    example:

    function checkbox1_Callback(h,eventdata,handles,varargin)

    if (get(h,'Value') == get(h,'Max'))

    % then checkbox is checked-take approriate actionelse

    % checkbox is not checked-take approriate action

    end

    Edit Tex tEdit t ext controls are fields tha t ena ble users to enter or m odify text str ings.

    Use edit text when you wan t t ext as input. The String property contains t he

    text entered by the user.

    To obta in th e string typed by the us er, get the String property in the callback.

    function edittext1_Callback(h,eventdata,handles,varargin)

    user_string = get(h,'string');% proceed with callback...

    Obtaining Numeric Data from an Edit Test Component

    MATLAB retu rns t he value of the edit t ext String property as a chara cter

    string. If you wan t user s to enter nu meric values, you mu st convert t he

    chara cters t o nu mbers. You can do th is using the str2double comma nd, wh ich

    converts strings t o doubles. If the u ser ent ers non-num eric chara cters,

    str2double re turns NaN.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    38/180

    1 Getting Started with GUIDE

    1-30

    You can use t he following code in t he edit t ext callback. It gets t he valu e of th e

    String property an d converts it to a d ouble. It th en checks if the converted

    value is NaN, indicating the user ent ered a non-numer ic chara cter (isnan) and

    displays an er ror dialog (errordlg).

    function edittext1_Callback(h,eventdata,handles,varargin)user_entry = str2double(get(h,'string'));

    if isnan(user_entry)

    errordlg('You must enter a numeric value','Bad Input','modal')

    end

    % proceed with callback...

    Triggering Callback Execution

    On U NIX systems, clicking on th e menu bar of the figure window cau ses th e

    edit t ext callback to execute. H owever, on Microsoft Windows system s, if an

    editable text box has focus, clicking on t he m enuba r does not cau se th e editable

    text callback r out ine to execute. This behavior is consistent with t he r espective

    platform conventions. Clicking on other component s in th e GUI execut e th e

    callback.

    Sta tic Tex tStatic text controls displays lines of text. Static text is typically used to label

    other contr ols, provide directions to th e user , or indicat e values a ssociated with

    a slider. Users cann ot cha nge sta tic text inter actively and th ere is no way to

    invoke th e callback routine associated with it.

    SlidersSliders accept n umer ic input within a specific ra nge by enabling the u ser t o

    move a sliding bar. User s move the bar by pressing th e mouse button an d

    dragging the slide, by clicking in the trough, or by clicking an arrow. Thelocation of th e bar indicates a n um eric value.

    Slider Orientation

    You can orient the slider either h orizontally or vert ically by setting th e relat ive

    width a nd h eight of th e Position property:

    • Horizonta l slider – width is greater th an h eight.

    • Vert ical slider – height is greater tha n width.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    39/180

    User Interface Controls

    1-31

    For example, these settings create a horizonta l slider.

    Current Value, Range, and Step Size

    There a re four properties tha t cont rol the ra nge and step size of the slider:

    • Value – conta ins th e current value of th e slider.

    • Max – defines th e maximum slider value.

    • Min – defines th e minimum slider value.

    • SliderStep – specifies the size of a s lider st ep with respect to th e ra nge.

    The Value property cont ains t he n um eric value of the slider. You can set t his

    proper ty to specify an in itial condit ion a nd qu ery it in t he slider’s callback to

    obtain the valu e set by th e user. F or example, your callback could cont ain t he

    statement .

    slider_value = get(handles.slider1,'Value');

    The Max and Min propert ies specify the s lider’s ra nge (Max - Min).

    The SliderStep property controls the amoun t th e slider Value property

    changes when you click th e mouse on t he ar row button or on th e slider t rough.

    Specify SliderStep as a two-elemen t vector. The defau lt, [0.01 0.10], provides

    a 1 percent chan ge for clicks on a n a rrow an d a 10 percent chan ge for clicks in

    the t rough. The actua l step size is a function of th e slider step a nd t he slider

    range.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    40/180

    1 Getting Started with GUIDE

    1-32

    Designing a Slider

    Suppose you want to creat e a slider with the following behavior:

    • Slider r an ge = 5 to 8

    • Arrow step size = 0.4

    • Trough step size = 1

    • Initial value = 6.5

    Fr om th ese values you need to determine an d set the Max, Min, SliderStep, and

    Value propert ies. You can do this by ad ding th e following code to th e

    initia lization section of th e app licat ion M-file (after th e creat ion of th e handles 

    structure).

    slider_step(1) = 0.4/(8-5);

    slider_step(2) = 1/(8-5);

    set(handles.slider1,'sliderstep',slider_step,...

      'max',8,'min',5,'Value',6.5)

    You can also assign t he slider properties using t he P roperty Inspector:

    • SliderStep, X .133

    • SliderStep, Y .333

    • Max 8

    • Min 5

    • Value 6.5

    Triggering Callback Execution

    The slider callback is execut ed when t he user releases the m ouse but ton.

    FramesFr ames a re boxes tha t enclose regions of a figur e window. Fra mes can m ake a

    user interface easier to under stan d by visually grouping related cont rols.

    Fr ames h ave no callback routines associated with th em an d only uicontrols can

    appea r within fram es (axes cannot).

    Placing Components on Top of Frames

    Fr ames a re opaque. If you add a frame after addin g component s tha t you want

    to be positioned within t he fram e, you need t o bring forward t hose component s.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    41/180

    User Interface Controls

    1-33

    Use the Bring to Front and Send to Back  operat ions in th e Layout  menu for

    this purpose.

    List Box es

    List boxes display a list of items and enable users to select one or more items.

    The String property conta ins t he list of strings displayed in th e list box. The

    first it em in th e list h as a n index of 1.

    The Value property cont ains t he index into the list of str ings tha t correspond

    to the selected item. If the u ser selects m ultiple items, then Value is a vector of

    indices.

    By defau lt, the first item in th e list is h ighlighted wh en t he list box is first

    displayed. If you do not wan t a ny item h ighlighted, th en set t he Value property

    to empty, [].

    The ListboxTop property defines which string in t he list displays as the t op

    most item wh en t he list box is not lar ge enough t o display all list ent ries.

    ListboxTop is an index int o the ar ra y of strings defined by the String property

    an d must h ave a value between 1 and th e num ber of str ings. Noninteger values

    are fixed t o the n ext lowest int eger.

    Single or Multiple Selection

    The values of the Min and Max properties determine whether users can make

    single or mu ltiple selections:

    • If Max – Min > 1, then list boxes allow multiple item selection.

    • If Max – Min

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    42/180

    1 Getting Started with GUIDE

    1-34

    scrollbar). This means the callback is executed after the first click of a

    double-click on a single item or when the user is ma king mu ltiple selections.

    In t hese situa tions, you need to add anoth er component, su ch as a Done  button

    (push but ton) and program its callback routine to query th e list box Value 

    property (and possibly the figure SelectionType pr opert y) inst ead of creat inga callback for th e list box. If you ar e using t he a ut omatically generat ed

    app licat ion M-file opt ion, you need to eith er:

    • Set t he list box Callback property to the empty str ing ('') and rem ove th e

    callback subfun ction from t he a pplication M-file.

    • Leave th e callback su bfunction stu b in th e application M-file so th at no code

    executes when users click on list box items.

    The first choice is best if you a re su re you will not use t he list box callback a nd

    you wan t t o minimize th e size an d efficiency of the a pplication M-file. However,

    if you think you m ay wan t t o define a callback for t he list box at s ome time, it

    is simpler to leave the callback stub in the M-file.

    See Th e Listbox Callback for an exam ple of how to progra m a list box to open

    files.

    List Box Examples

    See th e following exam ples for m ore inform at ion on u sing list boxes:

    • List Box Directory Reader – sh ows how to creat es a GU I th at displays the

    cont ent s of directories in a list box an d ena bles user s to open a var iety of file

    types by double-clicking on t he filenam e.

    • Accessing Work spa ce Var iables from a List Box – shows h ow to access

    variables in the MATLAB base workspace from a list box GUI.

    Popup M enusPopup m enus open t o display a list of choices when users p ress t he a rr ow.

    The String property cont ains t he list of string displayed in the popup m enu.

    The Value property conta ins th e index int o the list of str ings tha t corr espond

    to the selected item.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    43/180

    User Interface Controls

    1-35

    When n ot open, a popup m enu displays the curr ent choice, which is deter mined

    by the index cont ained in t he Value property. The first item in t he list has a n

    index of 1.

    Popup menu s are u seful when you want t o provide users with a nu mber of

    mut ually exclusive choices, but do not want to take u p th e amount of space thata series of radio butt ons r equires.

    Programming the Popup Menu

    You can pr ogram th e popup men u callback to work by checking only the index

    of the item selected (contained in t he Value property) or you can obtain t he

    actua l string conta ined in th e selected item.

    This callback checks th e index of the selected item a nd u ses a switch sta temen t

    to tak e action ba sed on the value. If th e conten ts of th e popup menu is fixed,

    then you can use th is approach.

    function varargout = popupmenu1_Callback(h,eventdata,handles,varargin)

    val = get(h,'Value');

    switch val

    case 1

    % The user selected the first item

    case 2

    % The user selected the second item

    % etc.

    This callback obtains th e actual str ing selected in th e popup m enu. It u ses the

    value to index into th e list of strings. This a pproach ma y be useful if your

    program dyna mically loads the conten ts of th e popup m enu based on user

    action a nd you need to obtain t he selected str ing. Note th at it is necessary to

    convert t he value retur ned by the String property from a cell arra y to a str ing.

    function varargout = popupmenu1_Callback(h,eventdata,handles,varargin)val = get(h,'Value');

    string_list = get(h,'String');

    selected_string = string_list{val}; % convert from cell array to string

    % etc.

    Ena bling or Disa bling ControlsYou can control wheth er a cont rol responds to mouse bu tton clicks by set ting

    the Enable property. Controls ha ve three stat es:

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    44/180

    1 Getting Started with GUIDE

    1-36

    • on – The control is operational

    • off – The contr ol is disabled a nd it s label (set by th e string property) is

    grayed out.

    • inactive – The cont rol is disabled, but its label is not grayed out .

    When a control is disabled, clicking on it with the left mouse button does not

    execut e its callback rout ine. However, th e left-click cau ses t wo oth er callback

    routines to execut e:

    • First t he figure WindowButtonDownFcn callback execut es

    • Then th e cont rol’s ButtonDownFcn callback executes

    A right m ouse but ton click on a d isabled cont rol posts a cont ext men u, if one is

    defined for tha t cont rol. See t he Enable property description for more details.

    AxesAxes ena ble your GUI t o display gra phics (e.g., graphs an d ima ges). Like all

    graph ics objects, axes ha ve properties tha t you can set t o cont rol many a spects

    of its beha vior an d a ppeara nce. See Axes Pr operties for gener al informa tion on

    axes objects.

    Axes Callbacks

    Axes are not uicontrol objects, but can be programmed to execute a callback

    when u sers click a m ouse button in th e axes. Use the axes ButtonDownFcn 

    property t o define th e callback.

    Plotting to Axes in GUIs

    GUIs tha t conta in axes should ensure th e Command-line acces sibi l i ty  option

    in th e Applicat ion Opt ions d ialog is set t o Callback  (the default). This ena bles

    you to issu e plott ing comm an ds from callbacks without explicitly specifying th etarget axes. See Command-Line Accessibility for more information about how

    th is option works.

    GUIs with Multiple Axes

    If a GUI has multiple axes, you should explicitly specify which axes you want

    to tar get when you issue plott ing comma nds. You can do this using t he axes 

    comman d and th e handles stru cture. For exam ple,

    axes(handles.axes1)

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    45/180

    User Interface Controls

    1-37

    mak es the axes whose Tag property is axes1 th e current axes, and t herefore th e

    tar get for plotting comma nds. You can switch t he curr ent axes whenever you

    want to tar get a different axes. See GUI with Mu ltiple Axes for and example

    that uses two axes.

    FigureFigures ar e the windows th at cont ain th e GUI you design with the Layout

    Editor. See the description of figure properties for information on what figure

    characteristics you can control.

    Displaying Plots in a Separate Figure

    To prevent a figure from becoming t he t arget of plotting comma nds issued at

    the command line or by oth er GUIs, you can set the HandleVisibility and

    IntegerHandle pr operties t o off. However, th is mean s th e figure is a lso

    hidden from plottin g comman ds issued by your GU I.

    To issue plotting comma nds from your GU I, you s hould create a figure a nd

    axes, saving the h an dles (you can store th em in the handles str uctur e). Youthen parent the a xes to the figure a nd t hen pa rent the gra phics objects created

    by the plotting comma nd t o the axes. The following steps su mma rize this

    approach:

    • Save th e han dle of the figure when you create it.

    • Create an axes, save its handle, and set i ts Parent property to th e figure

    handle.

    • Create the plot, and save the han dles, and set t heir Parent properties to the

    ha ndle of the a xes.

    The following code illustrates these steps.

    fHandle = figure('HandleVisibility','off','IntegerHandle','off',...

    'Visible','off');

    aHandle = axes('Parent',fHandle);

    pHandles = plot(PlotData,'Parent',aHandle);

    set(fHandle,'Visible','on')

    Note tha t n ot a ll plottin g comman ds accept property na me/property value

    specifications as arguments. Consult the reference page for the specific

    comma nd t o see what a rgumen ts you can specify.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    46/180

    1 Getting Started with GUIDE

    1-38

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    47/180

     

    2

    MATLAB GUIs

    Introduction  . . . . . . . . . . . . . . . . . . . . 2-2

    Creating GUIs with GUIDE   . . . . . . . . . . . . . 2 -3

    GUI Development En vironmen t . . . . . . . . . . . . 2-3

    Edit ing Version 5 GUIs w ith Version 6 GUIDE   . . . . 2-6

    Select in g GUIDE Application Options   . . . . . . . . 2-8

    Configur ing th e Applicat ion M-File . . . . . . . . . . . 2-8

    Resize Behavior   . . . . . . . . . . . . . . . . . . 2-10Mak ing Your GUI Nonr esizable . . . . . . . . . . . . . 2-10

    Allowing Pr oport iona l GUI Resizing . . . . . . . . . . . 2-10

    User -Specified Resize Oper at ion . . . . . . . . . . . . 2-11

    Comman d-Line Access ibi l i ty   . . . . . . . . . . . . 2-12

    Access Opt ions . . . . . . . . . . . . . . . . . . . . 2-12

    Figure Pr opert ies That Cont rol Access . . . . . . . . . . 2-12

    Usin g findobj . . . . . . . . . . . . . . . . . . . . 2-13

    Electing to Generate Only the FIG-File . . . . . . . . 2-14

    The Gen erated M-File . . . . . . . . . . . . . . . . 2-15

    Callback Fu nction Nam es an d Arguments . . . . . . . . 2-15Application Allows Only One Inst ance to Run . . . . . . . 2-18

    Using the System Backgroun d Colors . . . . . . . . . . 2-18

    Waiting for User Inpu t . . . . . . . . . . . . . . . . 2-20

    Renaming Appl icat ion F i les and Tags   . . . . . . . . 2-21

    Usin g Sa ve As . . . . . . . . . . . . . . . . . . . . 2-21

    Getting Everything Right . . . . . . . . . . . . . . . 2-21

    Cha nging Component Tag Pr operties . . . . . . . . . . 2-21

    Cha nging th e Nam e of Callback Subfunctions . . . . . . . 2-22

    Cha nging th e Nam e of the M-File and FIG-File . . . . . . 2-24

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    48/180

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    49/180

    Creating GUIs with GUIDE

    2-3

    Crea ting GUIs w ith GUIDE

    MATLAB implements GUIs as figure windows containing various styles of

    uicont rol objects. You m ust progra m each object to perform th e inten ded action

    when a ctivated by th e user of th e GUI. In add ition, you m ust be able to save

    an d lau nch your GU I. All of these t ask s ar e simplified by GUIDE , MATLAB’s

    graph ical user interface development environm ent.

    GUI Development EnvironmentThe process of implementing a GUI involves two basic tasks:

    • Laying out the GU I components

    • Pr ogram ming the GUI components

    GUIDE pr imarily is a set of layout tools. However, GUIDE also genera tes a n

    M-file th at cont ains code to hand le the initia lization an d lau nching of th e GUI.

    This M-file provides a fram ework for th e implemen ta tion of th e callbacks – the

    functions th at execut e when user s activat e component s in the GUI.

    The Implementation of a GUI

    While it is possible to write an M-file tha t cont ains a ll the comma nds to lay out

    a GUI, it is easier t o use GUIDE to lay out th e components intera ctively an d to

    generat e two files tha t save and lau nch the GUI:

    • A FIG-file – conta ins a complet e description of the GU I figur e an d a ll of its

    children (uicontrols and axes), as well as the values of all object properties.

    • An M-file – contains t he functions t ha t lau nch an d cont rol the GUI an d th e

    callbacks, which are defined a s subfun ctions. Th is M-file is referr ed to as th e

    application M -file in this docum enta tion.

    Note tha t t he a pplication M-file does not cont ain t he code tha t lays out t he

    uicontrols; this information is saved in the FIG-file.

    The following diagra m illustra tes th e part s of a GUI implement at ion.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    50/180

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    51/180

    Creating GUIs with GUIDE

    2-5

    You can elect t o have GUIDE generat e only th e FIG-file an d write t he

    applicat ion M-file your self. Keep in m ind t ha t th ere a re n o uicontrol creation

    comma nds in t he a pplication M-file; the layout information is cont ained in th e

    FIG-file generat ed by the La yout Editor.

    Beginning the Implementation Process

    To begin imp lemen ting your GUI, pr oceed to th e following sections:

    • Getting Sta rted with GU IDE – th e basics of using GUIDE.

    • Selecting GUIDE Applicat ion Options – set both F IG-file and M-file options.

    • Using th e Layout Editor – begin laying out the GU I.

    • Und ersta nding t he Applicat ion M-File – discussion of programm ing

    techniques u sed in th e a pplication M-file.

    • Applicat ion Exam ples – a collection of examples th at illustr at e techniques

    which a re u seful for implement ing GUIs.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    52/180

    2 MATLAB GUIs

    2-6

    Editing Version 5 GUIs w ith Version 6 GUIDE

    In MATLAB Version 5, GUIDE saved GU I layout s a s MAT-file/M-file pair s. In

    MATLAB Version 6, GUIDE saves GUI layouts as FIG-files. GUIDE also

    gener at es an M-file to progra m th e GUI callbacks, however, this M-file does not

    cont ain layout code.

    Use the following procedure to edit a Version 5 GUI with Version 6 GUIDE:

    1 Display the Version 5 GUI.

    2 Obtain th e ha ndle of the GUI figure. If th e figure’s ha ndle is hidden (i.e., the

    figure’s HandleVisibility property is set t o off), set the root

    ShowHiddenHandles property to on.

    set(0,'ShowHiddenHandles','on')

    Then get th e ha ndle from t he root’s Children property.

    h = get(0,'Children');

    This stat ement r etur ns th e han dles of all figures tha t exist when you issue

    th e comman d. For simplicity, ensure t ha t th e GUI is the only figure

    displayed.

    3 Pass the ha ndle as an argument to the guide comman d.

    guide(h)

    Saving the GUI in Version 6 GUIDE

    When you save th e edited GUI with Version 6 GUIDE, MATLAB creat es a

    FI G-file tha t conta ins a ll the la yout inform at ion. Th e origina l MAT-file/M-file

    combinat ion is no longer u sed. To display th e revised GUI, use t he open or

    hgload comma nd t o load the newly creat ed FIG-file, or you can ru n t he

    application M-file generated by GUIDE.

    Updating Callbacks

    Ensure that the Callback properties of the u icontrols in your GUI a re set t o the

    desired callba ck str ing or callback M-file nam e when you sa ve th e FIG-file. If

    your Version 5 GUI used a n M-file tha t cont ain ed a combin at ion of layout code

    an d callback routines, th en you should restr uctur e th e M-file to contain only

    th e comman ds needed t o initialize th e GUI an d th e callback fun ctions. The

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    53/180

    Editing Version 5 GUIs with Version 6 GUIDE

    2-7

    app licat ion M-file gener at ed by Version 6 GU IDE can provide a model of how

    to restr uctur e your code.

    Note By defau lt, GUIDE genera tes a n a pplication M-file ha ving the sam e

    na me as t he F IG-file saved with th e Layout Editor. When you a ctivate a GUIfrom t he Layout E ditor, GUIDE a ttem pts t o execute th is M-file to laun ch t he

    GUI.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    54/180

    2 MATLAB GUIs

    2-8

    Selecting GUIDE Application Options

    Issuing the guide command displays an empty Layout Editor with an un titled

    figure. Before adding components to the layout, you should configure the GUI

    us ing th e GUIDE Applicat ion Op tions dialog. Access t he dia log by selectin g

    Application Option s. .. from th e Layout Editor Tools  menu.

    Configur ing the App lica tion M -FileThe GU IDE Application Options dialog enables you to select wheth er you wan t

    GUIDE to generate only a FIG-file for your layout or both a FIG-file and its

    compa nion a pplication M-file. You can a lso select a n um ber of different

    behaviors for your GUI.

    The following section describes t he options in th is dialog:

    • Resize beha vior

    • Command-line accessibility

    • Gener at e .fig file only

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    55/180

    Selecting GUIDE Application Options

    2-9

    • Gener at e .fig file and .m file

    • Generat e callback function prototypes

    • Applicat ion a llows only one ins ta nce to ru n

    • Use system color scheme for background

    • Fu nction does not ret ur n u nt il applicat ion window dismissed

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    56/180

    2 MATLAB GUIs

    2-10

    Resize Behavior

    You can contr ol wheth er u sers can resize the figure window cont aining your

    GUI a nd how MATLAB h and les resizing. GUIDE provides th ree options:

    • Non-resizable  – u sers cann ot change t he window size (default ).

    • Proport ional  – MATLAB au tomatically rescales th e components in th e GUI

    in proportion to the new figure window size.

    • User-specif ied – program t he GUI to behave in a cert ain way when user s

    resize the figure window.

    The first two approaches simply set properties appr opriately and requ ire no

    other action. User-specif ied resizing requires you to write a callback routine

    th at recalculat e sizes and positions of the component s based on t he n ew figure

    size. The following sections discuss ea ch app roach.

    M a k ing Your GUI N onresizableCerta in types of GUIs a re typically nonresizable. Warnin g and simple question

    dialog boxes, particularly modal windows, are usually not resizable. After a

    simple intera ction, users dismiss th ese GUIs so cha nging their size is not

    necessary.

    Property Settings

    GUIDE sets t he following properties to create nonresizable GUIs:

    • Units properties of the figure, axes, and uicontrols should be set to

    characters (the Layout E ditor default) so the GUI displays a t t he corr ect

    size on different computers.

    • Resize figure property is set to off.

    • ResizeFcn figur e property does not r equire a callback routine.

    Allow ing Proportiona l GUI ResizingUse th is approach if you wan t to allow users t o resize the GUI a nd a re sat isfied

    with a beh avior th at simply scales each component’s size an d relat ive position

    in pr oport ion t o the new figure size. Note th at th e font size of component labels

    does n ot resize and, if the size is redu ced enough, th ese labels may become

    unreadable.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    57/180

    Resize Behavior

    2-11

    This appr oach works well with s imple GUI tools and dialog boxes tha t apply

    settings with out closing. Users m ay wan t t o resize th ese windows to better fit

    them on the screen, but th e precise layout of the GU I is not critical to its

    function.

    Property Settings

    GUIDE sets th e following properties t o creat e proportiona l resizing GUI s:

    • Units properties of the axes a nd u icontrols should be set t o normalized so

    the these components resize and r eposition a s th e figure window chan ges

    size.

    • Units propert y of th e figure sh ould be set to characters so the GUI displays

    at t he correct size at r un time.

    • Resize figure pr operty s et t o on (the default).

    • ResizeFcn figure pr opert y does not require a callback r outine.

    User-Specified Resize O pera tionYou can creat e GUIs th at accommodate resizing, while at th e same t ime

    maint ain t he ap peara nce and u sability of your original design by programm ing

    the figure ResizeFcn callback routine. Th is callback rout ine essent ially

    recalculat es th e size and position of each component based on t he n ew figure

    size.

    This appr oach to han dling figure resizing is used m ost typically in GUI-based

    applicat ions th at require user int eraction on an ongoing basis. Such a n

    applicat ion m ight cont ain a xes for displaying dat a a nd va rious component s

    whose position and size are critical to the successful use of the interface.

    Property Settings

    GUIDE sets th e following properties t o implement this style of GUI:

    • Units pr operties of the figure, axes, an d u icontrols should generally be set to

    characters so the GUI displays at t he correct size at ru nt ime.

    • Resize figure pr operty s et t o on (the default).

    • ResizeFcn figure pr opert y requires a callback r outine to ha ndle resizing.

    See The Address Book Resize Fu nction for an example of a user -written resize

    function.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    58/180

    2 MATLAB GUIs

    2-12

    Command-Line Accessibility

    When MATLAB creates a graph , the figur e and axes ar e included in t he list of

    children of th eir respective par ents a nd th eir han dles are available th rough

    commands such as findobj, set, and get. If you issue an other plotting

    comma nd, th e outp ut is directed to th e curr ent figur e and a xes.

    GUIs a re also creat ed in figure windows. Generally, you do not wan t GU I

    figures t o be available as ta rgets for gra phics out put, s ince issuing a plotting

    comma nd could direct th e outp ut t o th e GUI figure, resulting in the graph

    appea ring in th e middle of the GUI.

    In cont ra st, if you create a GUI th at conta ins an a xes and you wan t comma nds

    enter ed in th e comma nd window to display in t his axes, you sh ould enable

    command-line access.

    Access OptionsThe GUIDE Application Options dialog provides three options to control user

    access:

    • Callback  – the figure and axes are visible only from within callbacks

    (default).

    • Off  – pr event comma nd-line a ccess to th e GUI figur e.

    • On  – enable command-line access to the GUI figure.

    • User-specif ied – th e GUI uses t he values you set for the figur e

    HandleVisibility and IntegerHandle properties.

    Figure Properties That Control AccessThere ar e t wo figure pr operties th at cont rol comm an d-line accessibility of the

    figure:

    • HandleVisibility – det ermines wheth er t he figur e’s ha ndle is visible to

    commands that attempt to access the current figure.

    • IntegerHandle – deter mines if a figur e’s h an dle is an integer or a floating

    point value.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    59/180

    Command-Line Accessibility

    2-13

    HandleVisibility – Callback

    Setting HandleVisibility t o callback causes handles to be visible from

    with in callback rout ines or fun ctions invoked by callback rout ines, but n ot from

    within functions invoked from th e comma nd line.This provides a mean s t o

    protect GUIs from command-line users, while allowing callback routines to

    ha ve complete a ccess to object ha ndles. You sh ould use t his option if your GUI

    cont ains axes.

    HandleVisibility – Off

    Setting the HandleVisibility property t o off rem oves th e ha ndle of th e figure

    from th e list of root object children so it will not become the cur ren t figure

    (which is the t ar get for gra phics outp ut ). The ha ndle rema ins valid, however,

    so a comma nd t ha t sp ecifies the h an dle explicitly still works (such as

    close(1)). However, you cann ot use comma nds t ha t operat e only on the

    current figure or a xes. These command s include xlabel, ylabel, zlabel,

    title, gca, and gcf.

    HandleVisibi li ty – OnHa ndles are a lways visible when HandleVisibility is on.

    IntegerHandle

    Setting the IntegerHandle property to off causes MATLAB to assign

    nonreusa ble real-number ha ndles (e.g., 67.0001221...) instead of int egers. This

    greatly reduces the likelihood of someone accidently performing an operation

    on th e figure.

    Using findobjWhen you set t he Command-line access ibi l ity  t o off, the h and le of the GUI

    figure is hidden. This mean s you cann ot use findobj to located t he h an dles ofthe uicontr ols in th e GUI. As an a lterna tive, the applicat ion M-file creates an

    object han dle stru cture th at cont ains t he ha ndles of each uicont rol in t he GUI

    an d passes this str uctur e to subfunctions.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    60/180

    2 MATLAB GUIs

    2-14

    Electing to Genera te O nly the FIG-File

    Select Gene rate .fig f i le only  in t he GU IDE Application Opt ions d ialog if you

    do not want GUIDE t o genera te an applicat ion M-file. When you sa ve the GUI

    from t he La yout Editor, GUIDE creates a FIG-file, which you can redisplay

    using the open or hgload comman d.

    When you select t his option, you m ust set t he Callback proper ty of each

    component in your GUI to a st ring th at MATLAB can evaluat e and per form th e

    desired action. This st ring can be an expression or t he n ame of an M-file.

    Select th is option if you wa nt to follow a completely different progra mm ing

    par adigm th an t ha t genera ted by the applicat ion M-file.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    61/180

    The Generated M-File

    2-15

    The Genera ted M -File

    Select Gene rate .f ig f i le an d .m file in the GU IDE Application Options dialog

    if you want GUIDE to create both the FIG-file an d t he a pplicat ion M-file (this

    is the default). Once you have selected this option, you can select any of the

    following item s in t he fra me t o configur e th e M-file:

    • Generat e callback function prototypes

    • Applicat ion allows only one ins ta nce to ru n

    • Use system color scheme for background

    • Fu nction does not ret ur n u nt il applicat ion window dismissed

    Ca llba ck Function N a mes a nd Ar gumentsWhen you select Generate cal lback funct ion prototypes  in the GUIDE

    Applicat ion Options dialog, GUIDE adds a subfunction to th e a pplication

    M-file for a ny component you a dd to th e GUI (note tha t fram e an d sta tic text

    components do not use t heir Callback property and t herefore ha ve nosubfunction). You m ust then write t he code for t he callback in th is subfunction.

    GUIDE a lso adds a su bfunction wh enever you edit a callback routine from the

    Layout Editor’s right-click context menu an d when you a dd men us t o the GUI

    using the Menu Editor.

    Naming Callback Subfunctions

    When you a dd a component t o your GUI layout, GUIDE a ssigns a value to its

    Tag property, which is th en used t o genera te th e nam e of the callback.

    For example, the first push butt on you ad d to the layout is tagged pushbutton1.

    When genera ting t he a pplicat ion M-file, GUIDE adds a callback su bfunction

    called pushbutton1_Callback. If you d efine a ButtonDownFcn for t he sam epush button, GUIDE names its subfunction pushbutton1_ButtonDownFcn.

    Callback Function Syntax

    The callback function synt ax is of th e form

    function varargout = objectTag_Callback(h,eventdata,handles,varargin)

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    62/180

    2 MATLAB GUIs

    2-16

    The ar gument s ar e listed in t he following table.

    For example, if you create a layout ha ving a p ush butt on whose Tag property is

    set to pushbutton1, then GUIDE generates this subfunction h eader in t he

    app licat ion M-file.

    function varargout = pushbutton1_Callback(h,eventdata,handles,varargin)

    Assigning the Callback Property String

    When you first add a component to your GUI layout, its Callback property is

    set to the string . This strin g signals GUIDE to replace it with one

    th at calls th e appr opriat e callback subfunction in th e application M-file when

    you sa ve or activate th e GUI. For example, GUIDE sets th e Callback property

    for pushbutton1 uicontrol to

    my_gui('pushbutton1_Callback',gcbo,[],guidata(gcbo))

    where:

    • my_gui – is th e na me of th e app licat ion M-file.

    • pushbutton1_Callback – is th e na me of the callback r out ine subfunction

    defined in my_gui.

    • gcbo – is a comma nd t ha t r etur ns t he n am e of the callback object (i.e.,

    pushbutton1).

    • [] – is a place holder for t he curren tly unu sed eventdata argument .

    • guidata(gcbo) – returns the handles structure.

    Callback Function Arguments

    h The h an dle of th e object whose callback is executing.

    eventdata Emp ty, reserved for futu re u se.

    handles A structur e containing th e han dles of all components in t he

    GUI wh ose fieldna mes a re d efined by th e object’s Tag 

    property. Can also be used to pass da ta to oth er callback

    functions or the m ain pr ogra m.

    varargin A var iable-length list of ar gument s tha t you want t o pass to

    the callback function.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    63/180

    The Generated M-File

    2-17

    See Callback Function Syntax for more information on callback function

    argu ment s an d Renam ing Application Files and Tags for more informa tion on

    how to cha nge the n ames u sed by GUIDE.

    Adding Arguments to the Callback – varargin

    Callback subfunctions added by GUIDE require certa in argum ents, but h ave a

    variable-length ar gument list. Since th e last a rgum ent is varargin, you can

    add wha tever argum ents you want t o the su bfun ction. To pass th e additiona l

    arguments, edit the Callback property’s str ing to include th e ar gumen ts. For

    example, if the str ing added au tomatically to the Callback property is,

    my_gui('pushbutton1_Callback',gcbo,[],guidata(gcbo))

    change it using the P roperty Inspector to include the a dditiona l argumen ts.

    For example, chan ging th e Callback property to,

    my_gui('pushbutton1_Callback',gcbo,[],guidata(gcbo),arg1,arg2)

    in the Pr operty Inspector:

    The subfunction, pushbutton1_Callback has the syntax

    varargout = pushbutton1_Callback(h,eventdata,handles,varargin)

    so you can pass th e extr a input argu ment s without cha nging its function

    definit ion line.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    64/180

    2 MATLAB GUIs

    2-18

    Defining Output Arguments – varargout

    GUIDE defines callbacks to return a var iable number of ar gument s using

    varargout. See Passing Var iable Numbers of Argumen ts for genera l

    inform ation on u sing varargin and varargout.

    App lica tion Allow s Only O ne Instance to RunThis option a llows you to select bet ween t wo behaviors for t he GU I figur e:

    • Allow MATLAB to display only one ins ta nce of th e GUI a t a time.

    • Allow MATLAB to display mu ltiple inst an ces of the GU I.

    If you a llow only one in sta nce, MATLAB reuses t he exist ing GUI figure

    whenever t he comma nd t o lau nch th e GUI is issued. If a GUI a lready exists,

    MATLAB brings it to the foreground r ath er th an creating a n ew figur e.

    If you uncheck this option, MATLAB creates a new GUI figure whenever you

    issue the comma nd to launch th e GUI.

    Code in the Application M-File

    GUIDE implements this featu re by genera ting code in t he a pplication M-file

    that uses the openfig comma nd. The reuse or new str ing specifies one inst an ce

    or mu ltiple inst an ces of the GUI figure.

    fig = openfig(mfilename,'reuse');

    or

    fig = openfig(mfilename,'new');

    Note En sure tha t you h ave only one occurrence of openfig in your

    app licat ion M-file, including in commen ted lines.

    Using the System Ba ck ground ColorsThe color us ed for GUI component s varies on different comput er syst ems. This

    option en ables you t o make t he figur e backgroun d color t he sa me a s th e defau lt

    uicontrol background color, which is system dependent.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    65/180

    The Generated M-File

    2-19

    If you select Use system color scheme for background  (the default), GUIDE

    chan ges the figure ba ckground color to mat ch the color of th e GUI componen ts.

    The following figures illustr at e th e resu lts with (right) an d with out (left)

    system color matching.

    Code in the Application M-File

    GUIDE im plements t his featur e by generat ing code in t he a pplicat ion M-file

    tha t sets t he figur e background color to th e default u icontrol background color,

    which is system dependent .

    % Use system color scheme for figure:

    set(fig,'Color',get(0,'DefaultUicontrolBackgroundColor'));

    Note En sur e tha t you have only one occurrence of th is statem ent in your

    app licat ion M-file, including in comm ent ed lines.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    66/180

    2 MATLAB GUIs

    2-20

    Waiting for User InputThe GUIDE application option,

    Funct ion does n ot return unt i l appli cat ion w indow di smissed

    generat es an application M-file tha t is designed to wait for u ser inpu t. It doesthis by calling uiwait, which blocks furt her execut ion of th e M-file.

    While execut ion wa its, MATLAB processes th e event qu eue. This mea ns t ha t

    an y user-interactions with th e GUI (such a s clicking a pu sh but ton) can invoke

    callback routines, but th e execution strea m always ret ur ns to the a pplication

    M-file un til one of two event s occur s:

    • The GUI figure is deleted.

    • A callback for a n object in t he GU I figur e execut es a uiresume comma nd.

    This feat ur e provides a wa y to block t he MATLAB comma nd line un til the u ser

    responds to th e dialog box, but at th e same time, allows callback routines t o

    execut e. When u sed in conjunction with a modal dialog, you can restr ict u ser

    intera ction to t he d ialog.

    See Laun ching a Dialog to Confirm an Operat ion for a n example th at u ses this

    option.

    Code in the Application M-File

    GUIDE implements this featu re by genera ting code in t he a pplication M-file

    that uses the uiwait comman d

    % Wait for callbacks to run and window to be dismissed:

    uiwait(fig);

    where fig is the han dle of the GUI figur e.

    Note En sur e th at you have only one occurren ce of uiwait in your applicat ionM-file, including in comm ent ed lines.

  • 8/17/2019 Creating Graphical User Interfaces - Matlab

    67/180

    Renaming Application Files and Tags

    2-21

    Renaming Application Files and Tags

    It is often desirable t o use descriptive na mes for component Tag properties and

    callback subfunction n am es. GUIDE assigns a va lue to the Tag pr operty of

    every component you insert in your layout (e.g., pushbutton1) and then u ses

    this s tring t o nam e th e callback subfunction (e.g., pushbutton1_Callback).

    It is genera lly a good practice to select t he t ags a nd filena mes before a ctivat ing

    or s aving your GUI for the first time.

    Using Save AsWhen you select Save As  from th e Layout Editor File  menu , GUIDE also

    rena mes th e application M-file and reset s the