Products & Services Industries Academia Support User Community Company

Learn more about MATLAB   

Examples: Programming GUIDE GUI Components

See A Working GUI with Many Components in the GUIDE documentation for an example of a complete GUI that incorporates most of the controls described in the following sections.

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

maxVal = get(handles.checkbox1,'Max'); 
set(handles.checkbox1,'Value',maxVal);

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')
  uicontrol(hObject)
	return
end
% Proceed with callback...

Edit text controls lose focus when the user commits and edit (by typing Return or clicking away). The line uicontrol(hObject) restores focus to the edit text box. Although doing this is not needed for its callback to work, it is helpful in the event that user input fails validation. The command has the effect of selecting all the text in the edit text box.

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.

Table

A table can contain numbers, character data, and preset choices (drop-down menus). Each column must contain the same type of data. You can make a table or any column within it editable by the end user. You can specify column formats and give rows and columns consecutive numbers or label them individually. The number of rows and columns automatically adjust to reflect the size of the data matrix the table displays. Beside having callbacks common to most components (ButtonDownFcn, DeleteFcn, and KeypressFcn), tables have the following special callbacks:

These callbacks are unique to tables and are described below. Both issue event data.

Table CellEditCallbacks

If a table is user editable (because one or more columns have their ColumnEditable property set to true), the CellEditCallback fires every time the user changes the value of a table cell. The callback can use event data passed to it to identify which cell was changed, what the previous value for it was and what the new value is. For example, it can assess whether the new value is valid or not (e.g., numbers representing a person's height or weight must be positive); the callback can issue an error alert and then replace the invalid value with the previous value.

Table CellSelectionCallback

Every time the user selects a table cell, the table's CellSelectionCallback fires. This happens whether table cells are editable or not. When cells are not editable, users can drag across a range of cells to select them all. When cells are editable, users can select more than one cell at a time using Shift+click or Ctrl+click, but not by dragging. The indices for all currently selected cells are returned in the CellSelectionCallback eventdata structure. The callback fires every time the selection changes, and new event data is passed.

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.

Even when Resize behavior for the figure is Other (Use ResizeFcn), if components use normalized Units, they still automatically resize proportionally unless a ResizeFcn overrides that behavior. The following example shows how you can use a ResizeFcn to do more than that. The GUI repositions components automatically. Its panel's ResizeFcn proportionally adjusts the fontSize of a button's label.

  1. Create a GUI in GUIDE that contains a panel with two push buttons inside it. In the Property Inspector, name the buttons Button 1 and Button 2. Set the figure's Units to pixels and its Position to [420 520 150 190]. The GUI looks like this.

  2. Create callbacks for the two push buttons, and place the following line of code in each of them.

    set(gcbf,'Position',[420 520 150 190])

    This resets the GUI to its initial size, so you can experiment with resizing it manually.

  3. In the Property Inspector, set the Units of the panel and the two buttons to normalized. Also set the fontSize of both buttons to 10. Make sure that the fontUnits property for both buttons is set to points.

  4. Create a ResizeFcn callback for the panel by Clicking the pencil icon for the ResizeFcn in the Property Inspector and insert the following code into it.

    function uipanel1_ResizeFcn(hObject, eventdata, handles)
    .
    .
    .
    set(hObject,'Units','Points')               % Was normalized
    panelSizePts = get(hObject,'Position');     % Now in points
    panelHeight = panelSizePts(4);
    set(hObject,'Units','normalized');          % Now normalized again
    % Keep fontsize in constant ratio to height of panel
    newFontSize = 10 * panelHeight / 115;       % Calculated in points
    buttons = get(hObject,'Children');
    set(buttons(1),'FontSize',newFontSize);     % Resize the first button
    % Do not resize the other button for comparison

    This code adjusts the size of one of the buttons label (in this instance, the bottom one) when the figure resizes. It computes newFontSize as the ratio of the panel's current size to its original size (expressed in points) multiplied by the original button fontSize, 10 points. Then it sets one of the button's fontSize to that value.

  5. When you run the GUI, it looks like the previous figure. When you resize it to be smaller or larger, the text of one of the buttons shrinks or grows, as shown in the following illustration.

    When you click either button, the GUI and the buttons returns to their original size. Because all Units are normalized, no other code for proportional resizing is needed.

Nested panels resize from inner to outer (in child-to-parent order). For more information about resizing panels, see the uipanel properties reference page.

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.

When programming a button group, you do not code callbacks for the individual buttons; instead, use its SelectionChangeFcn callback to manage responses to selections. The following example, Programming a Button Group, illustrates how you use uibuttongroup event data to do this.

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:

Programming a Button Group

This example of a SelectionChangeFcn callback uses the Tag property of the selected object to choose the appropriate code to execute. The Tag property of each component is a string that identifies that component and must be unique in the GUI.

function uibuttongroup1_SelectionChangeFcn(hObject,eventdata)
switch get(eventdata.NewValue,'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

The hObject and eventdata arguments are available to the callback only if the value of the callback property is specified as a function handle. See the SelectionChangeFcn property on the Uibuttongroup Properties reference page for information about eventdata. See the uibuttongroup reference page and Color Palette for other examples.

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:

See Creating COM Objects in the MATLAB External Interfaces documentation to learn more about ActiveX controls.

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.

If you are reading this in the MATLAB Help browser, you can click the following links to display the GUIDE Layout Editor and the MATLAB Editor with a completed version of the following example.

If you modify the example GUI or its M-file and want to retain your changes, use File > Save as in the Layout Editor and save the files in a folder to which you have write access.

  1. To add the sample ActiveX control, click the ActiveX tool in the GUIDE Layout Editor and drag out an area to contain it. The dialog box opens.

  2. Select Mwsamp Control from the list box on the left side of the dialog box. A preview of it appears in the right side.

      Note   Clicking Create places a copy of the file Mwsamp_activex1 in your working folder. If you move your GUI files to a different folder, you should move the ActiveX controls they use with them.

  3. Click Create to 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 ActiveX Controls.

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

  5. 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:

    • Label, which contains the text that appears at the top of the control

    • Radius, the default radius of the circle, which is 20

  6. Locate the Click callback in the GUI M-file; select View Callbacks from the View menu and then select Click.

    GUIDE adds a new callback template, activex1_Click, to the end of the GUI M-file.

  7. Add the following code to the mswamp control's activex1_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 = floor(.9*hObject.radius); 
    hObject.label = ['Radius = ' num2str(hObject.radius)]; 
    refresh(handles.figure1); 
    
  8. Add the following commands to the end of the opening function, Mwsamp_OpeningFcn. 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

    • Gets the Value of the slider, which in this example is a number between 0 and 1, the default values of the slider's Min and Max properties.

    • Sets handles.activex1.radius equal to the Value times the default radius.

  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 folder 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 folder, 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.

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

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