Main Content

Callbacks for Specific Components

Note

The GUIDE environment will be removed in a future release. After GUIDE is removed, existing GUIDE apps will continue to run in MATLAB® but they will not be editable in GUIDE.

To continue editing an existing GUIDE app, see GUIDE Migration Strategies for information on how to help maintain compatibility of the app with future MATLAB releases. To create new apps interactively, Develop Apps Using App Designer instead.

Coding the behavior of a UI component involves specific tasks that are unique to the type of component you are working with. This topic contains simple examples of callbacks for each type of component. For general information about coding callbacks, see Write Callbacks in GUIDE or Create Callbacks for Apps Created Programmatically.

How to Use the Example Code

If you are working in GUIDE, then right-click on the component in your layout and select the appropriate callback property from the View Callbacks menu. Doing so creates an empty callback function that is automatically associated with the component. The specific function name that GUIDE creates is based on the component’s Tag property, so your function name might be slightly different than the function name in the example code. Do not change the function name that GUIDE creates in your code. To use the example code in your app, copy the code from the example’s function body into your function’s body.

Push Button

This code is an example of a push button callback function in GUIDE. Associate this function with the push button Callback property to make it execute when the end user clicks on the push button.

function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
display('Goodbye');
close(gcf);

The first line of code, display('Goodbye'), displays 'Goodbye' in the Command Window. The next line gets the UI window using gcf and then closes it.

Toggle Button

This code is an example of a toggle button callback function in GUIDE. Associate this function with the toggle button Callback property to make it execute when the end user clicks on the toggle button.

function togglebutton1_Callback(hObject,eventdata,handles)
% hObject    handle to togglebutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of togglebutton1
button_state = get(hObject,'Value');
if button_state == get(hObject,'Max')
	display('down');
elseif button_state == get(hObject,'Min')
	display('up');
end

The toggle button’s Value property matches the Min property when the toggle button is up. The Value changes to the Max value when the toggle button is depressed. This callback function gets the toggle button’s Value property and then compares it with the Max and Min properties. If the button is depressed, then the function displays 'down' in the Command Window. If the button is up, then the function displays 'up'.

Radio Button

This code is an example of a radio button callback function in GUIDE. Associate this function with the radio button Callback property to make it execute when the end user clicks on the radio button.

function radiobutton1_Callback(hObject, eventdata, handles)
% hObject    handle to radiobutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of radiobutton1

if (get(hObject,'Value') == get(hObject,'Max'))
	display('Selected');
else
	display('Not selected');
end

The radio button’s Value property matches the Min property when the radio button is not selected. The Value changes to the Max value when the radio button is selected. This callback function gets the radio button’s Value property and then compares it with the Max and Min properties. If the button is selected, then the function displays 'Selected' in the Command Window. If the button is not selected, then the function displays 'Not selected'.

Note

Use a button group to manage exclusive selection behavior for radio buttons. See Button Group for more information.

Check Box

This code is an example of a check box callback function in GUIDE. Associate this function with the check box Callback property to make it execute when the end user clicks on the check box.

function checkbox1_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox1

if (get(hObject,'Value') == get(hObject,'Max'))
	display('Selected');
else
	display('Not selected');
end

The check box’s Value property matches the Min property when the check box is not selected. The Value changes to the Max value when the check box is selected. This callback function gets the check box’s Value property and then compares it with the Max and Min properties. If the check box is selected, the function displays 'Selected' in the Command Window. If the check box is not selected, it displays 'Not selected'.

Edit Text Field

This code is an example of a callback for an edit text field in GUIDE. Associate this function with the uicontrol’s Callback property to make it execute when the end user types inside the text field.

function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents as double
input = get(hObject,'String');
display(input);

When the user types characters inside the text field and presses the Enter key, the callback function retrieves those characters and displays them in the Command Window.

To enable users to enter multiple lines of text, set the Max and Min properties to numeric values that satisfy Max - Min > 1. For example, set Max to 2, and Min to 0 to satisfy the inequality. In this case, the callback function triggers when the end user clicks on an area in the UI that is outside of the text field.

Retrieve Numeric Values

If you want to interpret the contents of an edit text field as numeric values, then convert the characters to numbers using the str2double function. The str2double function returns NaN for nonnumeric input.

This code is an example of an edit text field callback function that interprets the user’s input as numeric values.

function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents as a double
input = str2double(get(hObject,'String'));
if isnan(input)
  errordlg('You must enter a numeric value','Invalid Input','modal')
  uicontrol(hObject)
  return
else
  display(input);
end

When the end user enters values into the edit text field and presses the Enter key, the callback function gets the value of the String property and converts it to a numeric value. Then, it checks to see if the value is NaN (nonnumeric). If the input is NaN, then the callback presents an error dialog box.

Slider

This code is an example of a slider callback function in GUIDE. Associate this function with the slider Callback property to make it execute when the end user moves the slider.

function slider1_Callback(hObject, eventdata, handles)
% hObject    handle to slider1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine...
slider_value = get(hObject,'Value');
display(slider_value);

When the end user moves the slider, the callback function gets the current value of the slider and displays it in the Command Window. By default, the slider’s range is [0, 1]. To modify the range, set the slider’s Max and Min properties to the maximum and minimum values, respectively.

List Box

Populate Items in the List Box

If you are developing an app using GUIDE, use the list box CreateFcn callback to add items to the list box.

This code is an example of a list box CreateFcn callback that populates the list box with the items, Red, Green, and Blue.

function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns

% Hint: listbox controls usually have a white background on Windows.
if ispc && isequal(get(hObject,'BackgroundColor'), ...
    get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
set(hObject,'String',{'Red';'Green';'Blue'});
The last line, set(hObject,'String',{'Red';'Green';'Blue'}), populates the contents of the list box.

Change the Selected Item

When the end user selects a list box item, the list box’s Value property changes to a number that corresponds to the item’s position in the list. For example, a value of 1 corresponds to the first item in the list. If you want to change the selection in your code, then change the Value property to another number between 1 and the number of items in the list.

For example, you can use the handles structure in GUIDE to access the list box and change the Value property:

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

The first argument, handles.listbox1, might be different in your code, depending on the value of the list box Tag property.

Write the Callback Function

This code is an example of a list box callback function in GUIDE. Associate this function with the list box Callback property to make it execute when a selects an item in the list box.

function listbox1_Callback(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns contents
% contents{get(hObject,'Value')} returns selected item from listbox1
items = get(hObject,'String');
index_selected = get(hObject,'Value');
item_selected = items{index_selected};
display(item_selected);

When the end user selects an item in the list box, the callback function performs the following tasks:

  • Gets all the items in the list box and stores them in the variable, items.

  • Gets the numeric index of the selected item and stores it in the variable, index_selected.

  • Gets the value of the selected item and stores it in the variable, item_selected.

  • Displays the selected item in the MATLAB Command Window.

The example, Interactive List Box App in GUIDE shows how to populate a list box with directory names.

Pop-Up Menu

Populate Items in the Pop-Up Menu

If you are developing an app using GUIDE, use the pop-up menu CreateFcn callback to add items to the pop-up menu.

This code is an example of a pop-up menu CreateFcn callback that populates the menu with the items, Red, Green, and Blue.

function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns

% Hint: popupmenu controls usually have a white background on Windows.
if ispc && isequal(get(hObject,'BackgroundColor'),...
    get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
set(hObject,'String',{'Red';'Green';'Blue'});
The last line, set(hObject,'String',{'Red';'Green';'Blue'}), populates the contents of the pop-up menu.

Change the Selected Item

When the end user selects an item, the pop-up menu’s Value property changes to a number that corresponds to the item’s position in the menu. For example, a value of 1 corresponds to the first item in the list. If you want to change the selection in your code, then change the Value property to another number between 1 and the number of items in the menu.

For example, you can use the handles structure in GUIDE to access the pop-up menu and change the Value property:

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

The first argument, handles.popupmenu1, might be different in your code, depending on the value of the pop-up menu Tag property.

Write the Callback Function

This code is an example of a pop-up menu callback function in GUIDE. Associate this function with the pop-up menu Callback property to make it execute when the end user selects an item from the menu.

function popupmenu1_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns contents...
%        contents{get(hObject,'Value')} returns selected item...
items = get(hObject,'String');
index_selected = get(hObject,'Value');
item_selected = items{index_selected};
display(item_selected);

When the user selects an item in the pop-up menu, the callback function performs the following tasks:

  • Gets all the items in the pop-up menu and stores them in the variable, items.

  • Gets the numeric index of the selected item and stores it in the variable, index_selected.

  • Gets the value of the selected item and stores it in the variable, item_selected.

  • Displays the selected item in the MATLAB Command Window.

Panel

Make the Panel Respond to Button Clicks

You can create a callback function that executes when the end user right-clicks or left-clicks on the panel. If you are working in GUIDE, then right-click the panel in the layout and select View Callbacks > ButtonDownFcn to create the callback function.

This code is an example of a ButtonDownFcn callback in GUIDE.

function uipanel1_ButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to uipanel1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
display('Mouse button was pressed');
When the end user clicks on the panel, this function displays the text, 'Mouse button was pressed', in the Command Window.

Resize the Window and Panel

By default, GUIDE UIs cannot be resized, but you can override this behavior by selecting Tools > GUI Options and setting Resize behavior to Proportional.

When the UI window is resizable, the position of components in the window adjust as the user resizes it. If you have a panel in your UI, then the panel’s size will change with the window’s size. Use the panel’s SizeChangedFcn callback to make your app perform specific tasks when the panel resizes.

This code is an example of a panel’s SizeChangedFcn callback in a GUIDE app. When the user resizes the window, this function modifies the font size of static text inside the panel.

function uipanel1_SizeChangedFcn(hObject, eventdata, handles)
% hObject    handle to uipanel1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(hObject,'Units','Points')               
panelSizePts = get(hObject,'Position');     
panelHeight = panelSizePts(4);
set(hObject,'Units','normalized');          
newFontSize = 10 * panelHeight / 115;       
texth = findobj('Tag','text1');
set(texth,'FontSize',newFontSize);

If your UI contains nested panels, then they will resize from the inside-out (in child-to-parent order).

Note

To make the text inside a panel resize automatically, set the fontUnits property to 'normalized'.

Button Group

Button groups are similar to panels, but they also manage exclusive selection of radio buttons and toggle buttons. When a button group contains multiple radio buttons or toggle buttons, the button group allows the end user to select only one of them.

Do not code callbacks for the individual buttons that are inside a button group. Instead, use the button group’s SelectionChangedFcn callback to respond when the end user selects a button.

This code is an example of a button group SelectionChangedFcn callback that manages two radio buttons and two toggle buttons.

function uibuttongroup1_SelectionChangedFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in uibuttongroup1 
% eventdata  structure with the following fields
%	EventName: string 'SelectionChanged' (read only)
%	OldValue: handle of the previously selected object or empty
%	NewValue: handle of the currently selected object
% handles    structure with handles and user data (see GUIDATA)
switch get(eventdata.NewValue,'Tag') % Get Tag of selected object.
    case 'radiobutton1'
        display('Radio button 1');
    case 'radiobutton2'
        display('Radio button 2');
    case 'togglebutton1'
        display('Toggle button 1');
    case 'togglebutton2'
        display('Toggle button 2');
end

When the end user selects a radio button or toggle button in the button group, this function determines which button the user selected based on the button’s Tag property. Then, it executes the code inside the appropriate case.

Note

The button group’s SelectedObject property contains a handle to the button that user selected. You can use this property elsewhere in your code to determine which button the user selected.

Menu Item

The code in this section contains example callback functions that respond when the end user selects Edit > Copy > To File in this menu.

Figure window with a menu bar. The menu has two options, "File" and "Edit". The "Edit" option is selected and contains a submenu with items "Cut", "Copy", and "Paste". The "Copy" option is highlighted and contains another submenu with one item, "To File".

% --------------------------------------------------------------------
function edit_menu_Callback(hObject, eventdata, handles)
% hObject    handle to edit_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
display('Edit menu selected');

% --------------------------------------------------------------------
function copy_menu_item_Callback(hObject, eventdata, handles)
% hObject    handle to copy_menu_item (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
display('Copy menu item selected');

% --------------------------------------------------------------------
function tofile_menu_item_Callback(hObject, eventdata, handles)
% hObject    handle to tofile_menu_item (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[filename,path] = uiputfile('myfile.m','Save file name');
The function names might be different in your code, depending on the tag names you specify in the GUIDE Menu Editor.

The callback functions trigger in response to these actions:

  • When the end user selects the Edit menu, the edit_menu_Callback function displays the text, 'Edit menu selected', in the MATLAB Command Window.

  • When the end user hovers the mouse over the Copy menu item, the copy_menu_item_Callback function displays the text, 'Copy menu item selected', in the MATLAB Command Window.

  • When the end user clicks and releases the mouse button on the To File menu item, the tofile_menu_item_Callback function displays a dialog box that prompts the end user to select a destination folder and file name.

The tofile_menu_item_Callback function calls the uiputfile function to prompt the end user to supply a destination file and folder. If you want to create a menu item that prompts the user for an existing file, for example, if your UI has an Open File menu item, then use the uigetfile function.

When you create a cascading menu like this one, the intermediate menu items trigger when the mouse hovers over them. The final, terminating, menu item triggers when the mouse button releases over the menu item.

How to Update a Menu Item Check

You can add a check mark next to a menu item to indicate that an option is enabled. In GUIDE, you can select Check mark this item in the Menu Editor to make the menu item checked by default. Each time the end user selects the menu item, the callback function can turn the check on or off.

This code shows how to change the check mark next to a menu item.

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

The strcmp function compares two character vectors and returns true when they match. In this case, it returns true when the menu item’s Checked property matches the character vector, 'on'.

See Create Menus for GUIDE Apps for more information about creating menu items in GUIDE.

Table

This code is an example of the table callback function, CellSelectionCallback. Associate this function with the table CellSelectionCallback property to make it execute when the end user selects cells in the table.

function uitable1_CellSelectionCallback(hObject, eventdata, handles)
% hObject    handle to uitable1 (see GCBO)
% eventdata  structure with the following fields
%   Indices: row and column indices of the cell(s) currently selected
% handles    structure with handles and user data (see GUIDATA)
data = get(hObject,'Data');
indices = eventdata.Indices;
r = indices(:,1);
c = indices(:,2);
linear_index = sub2ind(size(data),r,c);
selected_vals = data(linear_index);
selection_sum = sum(sum(selected_vals))

When the end user selects cells in the table, this function performs the following tasks:

  • Gets all the values in the table and stores them in the variable, data.

  • Gets the indices of the selected cells. These indices correspond to the rows and columns in data.

  • Converts the row and column indices into linear indices. The linear indices allow you to select multiple elements in an array using one command.

  • Gets the values that the end user selected and stores them in the variable, selected_vals.

  • Sums all the selected values and displays the result in the Command Window.

This code is an example of the table callback function, CellEditCallback. Associate this function with the table CellEditCallback property to make it execute when the end user edits a cell in the table.

function uitable1_CellEditCallback(hObject, eventdata, handles)
% hObject    handle to uitable1 (see GCBO)
% eventdata  structure with the following fields
%	Indices: row and column indices of the cell(s) edited
%	PreviousData: previous data for the cell(s) edited
%	EditData: string(s) entered by the user
%	NewData: EditData or its converted form set on the Data property.
% Empty if Data was not changed
% Error: error string when failed to convert EditData
data = get(hObject,'Data');
data_sum = sum(sum(data))
When the end user finishes editing a table cell, this function gets all the values in the table and calculates the sum of all the table values. The ColumnEditable property must be set to true in at least one column to allow the end user to edit cells in the table.

Axes

The code in this section is an example of an axes ButtonDownFcn that triggers when the end user clicks on the axes.

Axes in a figure window

function axes1_ButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to axes1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
pt = get(hObject,'CurrentPoint')
The coordinates of the pointer display in the MATLAB Command Window when the end user clicks on the axes (but not when that user clicks on another graphics object parented to the axes).

Note

Most MATLAB plotting functions clear the axes and reset a number of axes properties, including the ButtonDownFcn, before plotting data. To create an interface that lets the end user plot data interactively, consider providing a component such as a push button to control plotting. Such components’ properties are unaffected by the plotting functions. If you must use the axes ButtonDownFcn to plot data, then use functions such as line, patch, and surface.

Related Topics