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 slider1_Callback.

    Function Shortcut

    Add the following code to the function:

    %obtains the slider value from the slider component
    sliderValue = get(handles.slider1,'Value');
     
    %puts the slider value into the edit text component
    set(handles.slider_editText,'String', num2str(sliderValue));
     
    % Update handles structure
    guidata(hObject, handles);
  2. Now, let’s add the following code to the slider_editText_Callback function:

    %get the string for the editText component
    sliderValue = get(handles.slider_editText,'String');
     
    %convert from string to number if possible, otherwise returns empty
    sliderValue = str2num(sliderValue);
     
    %if user inputs something is not a number, or if the input is less than 0
    %or greater than 100, then the slider value defaults to 0
    if (isempty(sliderValue) || sliderValue < 0 || sliderValue > 100)
        set(handles.slider1,'Value',0);
        set(handles.slider_editText,'String','0');
    else
        set(handles.slider1,'Value',sliderValue);
    end
  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:

    Slider GUI

  2. Now, try to put in different types of inputs to test the GUI. Any input that is not a number, less than zero, or greater than 100 should default the slider to a value of zero.

  3. And that’s it. Those are the basics of using a Slider component. You can explore the other options that the slider has to offer through the Property Inspector. For instance, you can use the SliderStep property to customize how far you want the slider to move when you press the left and right arrow, or when you click on the scroll bar.

This is the end of the tutorial.

Source files can be downloaded here.

Pages: 1 2