Examples: Programming GUIDE GUI Components

Push Button

This example contains only a push button. Clicking the button, closes the GUI.

This is the push button's Callback callback. It displays the string Goodbye at the command line and then closes the GUI.

function pushbutton1_Callback(hObject, eventdata, handles)
display Goodbye
close(handles.figure1);

Adding an Image to a Push Button or Toggle Button

To add an image to a push button or toggle button, assign the button's CData property an m-by-n-by-3 array of RGB values that defines RGB (Truecolor) Images. For example, the array a defines 16-by-64 truecolor image using random values between 0 and 1 (generated by rand).

a(:,:,1) = rand(16,64);
a(:,:,2) = rand(16,64);
a(:,:,3) = rand(16,64);
set(hObject,'CData',a)

To add the image when the button is created, add the code to the button's CreateFcn callback. You may want to delete the value of the button's String property, which would usually be used as a label.

See ind2rgb for information on converting a matrix X and corresponding colormap, i.e., an (X, MAP) image, to RGB (truecolor) format.

Toggle Button

The callback for a toggle button needs to query the toggle button to determine what state it is in. The Value property is equal to the Max property when the toggle button is pressed and equal to the Min property when the toggle button is not pressed.

The following code illustrates how to program the callback in the GUI M-file.

function togglebutton1_Callback(hObject, eventdata, handles)
button_state = get(hObject,'Value');
if button_state == get(hObject,'Max')
	% Toggle button is pressed, take approperiate action
   ...
elseif button_state == get(hObject,'Min')
	% Toggle button is not pressed, take appropriate action
    ...
end

You can also change the state of a toggle button programmatically by setting the toggle button Value property to the value of its Max or Min property. This example illustrates a possible syntax for such an assignment.

set(handles.togglebutton1,'Value','Max')

puts the toggle button with Tag property togglebutton1 in the pressed state.

Radio Button

You can determine the current state of a radio button from within its Callback callback by querying the state of its Value property. If the radio button is selected, its Value property is equal to its Max property. If the radio button is not selected, it is equal to its Min property. This example illustrates such a test.

function radiobutton1_Callback(hObject, eventdata, handles)
if (get(hObject,'Value') == get(hObject,'Max'))
	% Radio button is selected, take appropriate action
else
	% Radio button is not selected, take appropriate action
end

You can also change the state of a radio button programmatically by setting the radio button Value property to the value of the Max or Min property. This example illustrates a possible syntax for such an assignment.

set(handles.radiobutton1,'Value','Max')

selects the radio button with Tag property radiobutton1 and deselects the previously selected radio button.

Check Box

You can determine the current state of a check box from within its callback by querying the state of its Value property. The Value property is equal to the Max property when the check box is checked and equal to the Min property when the check box is not checked. This example illustrates such a test.

function checkbox1_Callback(hObject, eventdata, handles)
if (get(hObject,'Value') == get(hObject,'Max'))
	% Checkbox is checked-take approriate action
else
	% Checkbox is not checked-take approriate action
end

You can also change the state of a check box programmatically by setting the check box Value property to the value of the Max or Min property. This example illustrates a possible syntax for such an assignment.

set(handles.checkbox1,'Value','Max')

puts the check box with Tag property checkbox1 in the checked state.

Edit Text

To obtain the string a user types in an edit box, get the String property in the Callback callback.

function edittext1_Callback(hObject, eventdata, handles)
user_string = get(hObject,'String');
% Proceed with callback

If the edit text Max and Min properties are set such that Max - Min > 1, the user can enter multiple lines. For example, setting Max to 2, with the default value of 0 for Min, enables users to enter multiple lines.

Retrieving Numeric Data from an Edit Text Component

MATLAB® software returns the value of the edit text String property as a character string. If you want users to enter numeric values, you must convert the characters to numbers. You can do this using the str2double command, which converts strings to doubles. If the user enters nonnumeric characters, str2double returns NaN.

You can use the following code in the edit text callback. It gets the value of the String property and converts it to a double. It then checks whether the converted value is NaN (isnan), indicating the user entered a nonnumeric character and displays an error dialog (errordlg).

function edittext1_Callback(hObject, eventdata, handles)
user_entry = str2double(get(hObject,'string'));
if isnan(user_entry)
	errordlg('You must enter a numeric value','Bad Input','modal')
	return
end
% Proceed with callback...

Triggering Callback Execution

If the contents of the edit text component have been changed, clicking inside the GUI but outside the edit text causes the edit text callback to execute. The user can also press Enter for an edit text that allows only a single line of text, or Ctrl+Enter for an edit text that allows multiple lines.

Available Keyboard Accelerators

GUI users can use the following keyboard accelerators to modify the content of an edit text. These accelerators are not modifiable.

Slider

You can determine the current value of a slider from within its callback by querying its Value property, as illustrated in the following example:

function slider1_Callback(hObject, eventdata, handles)
slider_value = get(hObject,'Value');
% Proceed with callback...

The Max and Min properties specify the slider's maximum and minimum values. The slider's range is Max - Min.

List Box

When the list box Callback callback is triggered, the list box Value property contains the index of the selected item, where 1 corresponds to the first item in the list. The String property contains the list as a cell array of strings.

This example retrieves the selected string. It assumes listbox1 is the value of the Tag property. Note that it is necessary to convert the value returned from the String property from a cell array to a string.

function listbox1_Callback(hObject, eventdata, handles)
index_selected = get(hObject,'Value');
list = get(hObject,'String');
item_selected = list{index_selected}; % Convert from cell array
                                      % to string

You can also select a list item programmatically by setting the list box Value property to the index of the desired item. For example,

set(handles.listbox1,'Value',2)

selects the second item in the list box with Tag property listbox1.

Triggering Callback Execution

MATLAB software executes the list box's Callback callback after the mouse button is released or after certain key press events:

If the user double-clicks, the callback executes after each click. The software sets the figure SelectionType property to normal on the first click and to open on the second click. The callback can query the figure SelectionType property to determine if it was a single or double click.

List Box Examples

See the following examples for more information on using list boxes:

Pop-Up Menu

When the pop-up menu Callback callback is triggered, the pop-up menu Value property contains the index of the selected item, where 1 corresponds to the first item on the menu. The String property contains the menu items as a cell array of strings.

Using Only the Index of the Selected Menu Item

This example retrieves only the index of the item selected. It uses a switch statement to take action based on the value. If the contents of the pop-up menu are fixed, then you can use this approach. Else, you can use the index to retrieve the actual string for the selected item.

function popupmenu1_Callback(hObject, eventdata, handles)
val = get(hObject,'Value');
switch val
case 1
% User selected the first item
case 2
% User selected the second item
% Proceed with callback...

You can also select a menu item programmatically by setting the pop-up menu Value property to the index of the desired item. For example,

set(handles.popupmenu1,'Value',2)

selects the second item in the pop-up menu with Tag property popupmenu1.

Using the Index to Determine the Selected String

This example retrieves the actual string selected in the pop-up menu. It uses the pop-up menu Value property to index into the list of strings. This approach may be useful if your program dynamically loads the contents of the pop-up menu based on user action and you need to obtain the selected string. Note that it is necessary to convert the value returned by the String property from a cell array to a string.

function popupmenu1_Callback(hObject, eventdata, handles)
val = get(hObject,'Value');
string_list = get(hObject,'String');
selected_string = string_list{val}; % Convert from cell array
                                    % to string
% Proceed with callback...

Panel

Panels group GUI components and can make a GUI easier to understand by visually grouping related controls. A panel can contain panels and button groups as well as axes and user interface controls such as push buttons, sliders, pop-up menus, etc. The position of each component within a panel is interpreted relative to the lower-left corner of the panel.

Generally, if the GUI is resized, the panel and its components are also resized. However, you can control the size and position of the panel and its components. You can do this by setting the GUI Resize behavior to Other (Use ResizeFcn) and providing a ResizeFcn callback for the panel.

Button Group

Button groups are like panels except that they manage exclusive selection behavior for radio buttons and toggle buttons. If a button group contains a set of radio buttons, toggle buttons, or both, the button group allows only one of them to be selected. When a user clicks a button, that button is selected and all others are deselected.

The following figure shows a button group with two radio buttons and two toggle buttons. Radio Button 1 is selected.

If a user clicks the other radio button or one of the toggle buttons, it becomes selected and Radio Button 1 is deselected. The following figure shows the result of clicking Toggle Button 2.

The button group's SelectionChangeFcn callback is called whenever a selection is made. Its hObject input argument contains the handle of the selected radio button or toggle button.

If you have a button group that contains a set of radio buttons and toggle buttons and you want:

This example of a SelectionChangeFcn callback uses the Tag property of the selected object to choose the appropriate code to execute. For GUIDE GUIs, unlike other callbacks, the hObject argument of the SelectionChangeFcn callback contains the handle of the selected radio button or toggle button.

function uibuttongroup1_SelectionChangeFcn(hObject,...
    eventdata,handles)
switch get(hObject,'Tag')   % Get Tag of selected object
    case 'radiobutton1'
        % Code for when radiobutton1 is selected.
    case 'radiobutton2'
        % Code for when radiobutton2 is selected.
    case 'togglebutton1'
        % Code for when togglebutton1 is selected.
    case 'togglebutton2'
        % Code for when togglebutton2 is selected.
    % Continue with more cases as necessary.
    otherwise
        % Code for when there is no match.
end

See the uibuttongroup reference page for another example.

Axes

Axes components enable your GUI to display graphics, such as graphs and images. This topic briefly tells you how to plot to axes components in your GUI.

Plotting to an Axes

In most cases, you create a plot in an axes from a callback that belongs to some other component in the GUI. For example, pressing a button might trigger the plotting of a graph to an axes. In this case, the button's Callback callback contains the code that generates the plot.

The following example contains two axes and two buttons. Clicking one button generates a plot in one axes and clicking the other button generates a plot in the other axes. The following figure shows these components as they might appear in the Layout Editor.

  1. Add this code to the Plot 1 push button's Callback callback. The surf function produces a 3-D shaded surface plot. The peaks function returns a square matrix obtained by translating and scaling Gaussian distributions.

    surf(handles.axes1,peaks(35));
  2. Add this code to the Plot 2 push button's Callback callback. The contour function displays the contour plot of a matrix, in this case the output of peaks.

    contour(handles.axes2,peaks(35));
  3. Run the GUI by selecting Run from the Tools menu.

  4. Click the Plot 1 button to display the surf plot in the first axes. Click the Plot 2 button to display the contour plot in the second axes.

See GUI with Multiple Axes for a more complex example that uses two axes.

If your GUI contains axes, you should make sure that the Command-line accessibility option in the GUI Options dialog box is set to Callback (the default). From the Layout Editor select Tools > GUI Options > Command Line Accessibility: Callback. See Command-Line Accessibility for more information about how this option works.

Creating Subplots

Use the subplot function to create axes in a tiled pattern. If your GUIDE-generated GUI contains components other than the subplots, the subplots must be contained in a panel.

As an example, the following code uses the subplot function to create an axes with two subplots in the panel with Tag property uipanel1. This code is part of the Plot push button Callback callback. Each time you press the Plot button, the code draws a line in each subplot. a1 and a2 are the handles of the subplots.

a1=subplot(2,1,1,'Parent',handles.uipanel1); 
plot(a1,rand(1,10),'r'); 
a2=subplot(2,1,2,'Parent',handles.uipanel1); 
plot(a2,rand(1,10),'b'); 

For more information about subplots, see the subplot reference page. For information about adding panels to your GUI, see Adding Components to the GUIDE Layout Area.

ActiveX® Control

This example programs a sample ActiveX® control Mwsamp Control. It first enables a user to change the radius of a circle by clicking on the circle. It then programs a slider on the GUI to do the same thing.

This topic also discusses:

Programming an ActiveX® Control

The sample ActiveX control Mwsamp Control contains a circle in the middle of a square. This example programs the control to change the circle radius when the user clicks the circle, and to update the label to display the new radius.

  1. Add the sample ActiveX control Mwsamp to your GUI and resize it to approximately the size of the square shown in the preview pane. The following figure shows the ActiveX control as it appears in the Layout Editor.

    If you need help adding the component, see Adding Components to the GUIDE Layout Area.

  2. Activate the GUI by clicking the button on the toolbar and save the GUI when prompted. GUIDE displays the GUI shown in the following figure and opens the GUI M-file.

    active x control

  3. View the ActiveX Properties with the Property Inspector. Select the control in the Layout Editor, and then select Property Inspector from the View menu or by clicking the Property Inspector button on the toolbar.

    The following figure shows properties of the mwsamp ActiveX control as they appear in the Property Inspector. The properties on your system may differ.

    Property inspector showing label and radius properties

    This ActiveX control mwsamp has two properties:

  4. Add the following code to the mswamp control's Click callback. This code programs the ActiveX control to change the circle radius when the user clicks the circle, and updates the label to display the new radius.

    hObject.radius = .9*hObject.radius;
    hObject.label = ['Radius = ' num2str(hObject.radius)];
    refresh(handles.figure1);

    To locate the Click callback in the GUI M-file, select View Callbacks from the View menu and then select Click.

  5. Add the following commands to the opening function. This code initializes the label when you first open the GUI.

    handles.activex1.label = ...
    ['Radius = ' num2str(handles.activex1.radius)];

Save the M-file. Now, when you open the GUI and click the ActiveX control, the radius of the circle is reduced by 10 percent and the new value of the radius is displayed. The following figure shows the GUI after clicking the circle six times.

GUI control for radius set to 9

If you click the GUI enough times, the circle disappears.

Programming a User Interface Control to Update an ActiveX® Control

This topic continues the previous example by adding a slider to the GUI and programming the slider to change the circle radius. This example must also update the slider if the user clicks the circle.

  1. Add a slider to your layout and then add the following code to the slider1 Callback callback:

    handles.activex1.radius = ...
        get(hObject,'Value')*handles.default_radius;
    handles.activex1.label = ...
        ['Radius = ' num2str(handles.activex1.radius)];
    refresh(handles.figure1);

    The first command

  2. In the opening function, add the default radius to the handles structure. The activex1_Click callback uses the default radius to update the slider value if the user clicks the circle.

    handles.default_radius = handles.activex1.radius;
  3. In the activex1_Click callback, reset the slider's Value each time the user clicks the circle in the ActiveX control. The following command causes the slider to change position corresponding to the new value of the radius.

    set(handles.slider1,'Value',...
        hObject.radius/handles.default_radius);

When you open the GUI and move the slider by clicking and dragging, the radius changes to a new value between 0 and the default radius of 20, as shown in the following figure.

GUI control for radius of 14

Viewing the Methods for an ActiveX® Control

To view the available methods for an ActiveX control, you first need to obtain the handle to the control. One way to do this is the following:

  1. In the GUI M-file, add the command keyboard on a separate line of the activex1_Click callback. The command keyboard puts MATLAB software in debug mode and pauses at the activex1_Click callback when you click the ActiveX control.

  2. Run the GUI and click the ActiveX control. The handle to the control is now set to hObject.

  3. To view the methods for the control, enter

    methodsview(hObject)

    This displays the available methods in a new window, as shown in the following figure.

    Methods of class COM.mwsamp.mwsampctrol.1.release

    Alternatively, you can enter

    methods(hObject)

    which displays the available methods in the MATLAB Command Window.

For more information about methods for ActiveX controls, see Using Methods in the External Interfaces documentation. See the reference pages for methodsview and methods for more information about these functions.

Saving a GUI That Contains an ActiveX® Control

When you save a GUI that contains ActiveX controls, GUIDE creates a file in the current directory for each such control. The filename consists of the name of the GUI followed by an underscore (_) and activexn, where n is a sequence number. For example, if the GUI is named mygui, then the filename would be mygui_activex1. The filename does not have an extension.

Compiling a GUI That Contains an ActiveX® Control

If you use the MATLAB Compiler mcc command to compile a GUI that contains an ActiveX control, you must use the -a flag to add the ActiveX file, which GUIDE saves in the current directory, to the CTF archive. Your command should be similar to

mcc -m mygui -a mygui_activex1

where mygui_activex1 is the name of the ActiveX file. See the MATLAB Compiler™ documentation for more information. If you have more than one such file, use a separate -a flag for each file. You must have installed the MATLAB Compiler to compile a GUI.

Menu Item

The Menu Editor generates an empty callback subfunction for every menu item, including menu titles.

Programming a Menu Title

Because clicking a menu title automatically displays the menu below it, you may not need to program callbacks at the title level. However, the callback associated with a menu title can be a good place to enable or disable menu items below it.

Consider the example illustrated in the following picture.

copy to file menu

When a user selects the to file option under the Edit menu's Copy option, only the to file callback is required to perform the action.

Suppose, however, that only certain objects can be copied to a file. You can use the Copy item Callback callback to enable or disable the to file item, depending on the type of object selected.

Opening a Dialog Box from a Menu Callback

The Callback callback for the to file menu item could contain code such as the following to display the standard dialog box for saving files.

[file,path] = uiputfile('animinit.m','Save file name');

'Save file name' is the dialog box title. In the dialog box, the filename field is set to animinit.m, and the filter set to M-files (*.m). For more information, see the uiputfile reference page.

menu editor with select all item shown

Updating a Menu Item Check

A check is useful to indicate the current state of some menu items. If you selected Check mark this item in the Menu Editor, the item initially appears checked. Each time the user selects the menu item, the callback for that item must turn the check on or off. The following example shows you how to do this by changing the value of the menu item's Checked property.

if strcmp(get(hObject, 'Checked'),'on')
    set(hbject,'Checked','off');
else 
    set(hObject,'Checked','on');
end

hObject is the handle of the component, for which the callback was triggered. The strcmp function compares two strings and returns logical 1 (true) if the two are identical and logical 0 (false) otherwise.

Use of checks when the GUI is first displayed should be consistent with the display. For example, if your GUI has an axes that is visible when a user first opens it and the GUI has a Show axes menu item, be sure to set the menu item's Checked property on when you create it so that a check appears next to the Show axes menu item initially.

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS