Writing the Code for the GUI

Matlab automatically generates an .m file to go along with the figure that you just put together. The .m file is where we attach the appropriate code to the callback of each component. For the purposes of this tutorial, we are primarily concerned only with the callback functions. You don’t have to worry about any of the other function types.

  1. Open up the .m file that was automatically generated when you saved your GUI. In the Matlab editor, click on the Function Icon icon, which will bring up a list of the functions within the .m file. Select popupmenu1_Callback.

    Function Shortcut

    Add the following code to the function:

    %gets the selected option
    switch get(handles.popupmenu1,'Value')   
        case 1
            set(handles.testing_staticText,'FontSize',8);
        case 2
            set(handles.testing_staticText,'FontSize',10);
        case 3
            set(handles.testing_staticText,'FontSize',12);
        case 4
            set(handles.testing_staticText,'FontSize',14);
        case 5
            set(handles.testing_staticText,'FontSize',16);
        otherwise
    end
  2. Lets quickly go over the code now. The following line of code gets the option that the user selected. Remember that in the visual layout of the GUI, we designated five different font sizes for the Pop-up Menu component, giving us five different options for the Pop-up Menu. So for example, if the user selected a font size of 8 (which was the first option in the Pop-up Menu), then the following line of code would return a value of 1. If the user selected a font size of 10, then the value returned would be 2, and so on.

    get(handles.popupmenu1,'Value')

    Depending on the option selected, the font of the Static Text component will be adjusted using the following line of code for each case statement:

    %where ## is the appropiate fontsize value
    set(handles.testing_staticText,'FontSize',##);
  3. Save your m-file!

Run and Test the GUI

Now that we’ve completed both the visual and code aspects of the GUI, its time to run the GUI to make sure it works.

  1. From the m-file editor, you can click on the Save and Run Icon icon to save and run the GUI. Alternatively, from the GUIDE editor, you can click on the play button to launch the GUI. The following GUI should appear once you click the icon:

    Pop-up Menu

  2. Go ahead and try selecting different font sizes. If everything was done correctly, you should see the font size of the sample text change accordingly.

    Pop-up Menu Expanded

  3. And that’s it. Those are the basics of using a Pop-up Menu component. You can explore the other options that the slider has to offer through the Property Inspector.

This is the end of the tutorial.

Source files can be downloaded here.

Pages: 1 2