Callbacks for Specific Components
figure
uicontrol('Style','Listbox',...
'String',{'Red';'Green';'Blue'},...
'Position',[40 70 80 50]);
end
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 UI
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.