MATLAB Creating Graphical User Interfaces

(Barry) #1
Callbacks for Specific Components

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 UI
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 end 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 string value of the selected item and stores it in the variable,
    item_selected.

  • Displays the selected item in the MATLAB Command Window.

Free download pdf