MATLAB: How to get a listbox value using a push button callback

callbackguilistboxpushbutton

Hi,
I am coding a simple GUI with some list boxes and push buttons. I want to use the push button callback to read the listbox value, however I can't figure out how to 'read' the listbox value using the push button callback. I understand how to use the pushbutton callback on its own, but not how to link it to the listbox.
My code is below (version R2016b with all toolboxes) – can anyone offer some help?
Thanks!
function my_gui
%%GUI interface
S.fh = figure('units','normalized',...
'position',[0.0 0.3 0.5 0.65],...
'menubar','none',...
'name','my_gui');
S.input_list = uicontrol('style','listbox',...
'unit','normalized',...
'position',[0.05 0.2 0.35 0.65],...
'string',{'A';'B';'C'},...
'fontunits','normalized',...
'Callback',@input_list_Callback);
S.output_list = uicontrol('style','listbox',...
'unit','normalized',...
'position',[0.60 0.2 0.35 0.65],...
'string',{},...
'fontunits','normalized',...
'Callback',@output_list_Callback);
S.pb1 = uicontrol('style','push',...
'unit','normalized',...
'position',[0.44 0.7 0.12 0.1],...
'string','Add',...
'fontunits','normalized',...
'Callback',@pb1_Callback);
S.pb2 = uicontrol('style','push',...
'unit','normalized',...
'position',[0.44 0.55 0.12 0.1],...
'string','Remove',...
'fontunits','normalized',...
'Callback',@pb2_Callback);
function pb1_Callback(hObject, eventdata, handles)
% hObject handle to pb1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB


% handles structure with handles and user data (see GUIDATA)


display('pb1')
function pb2_Callback(hObject, eventdata, handles)
% hObject handle to pb2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
display('pb2');
function input_list_Callback(hObject, eventdata, handles)
% hObject handle to input_list (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vals=get(hObject,'string')

Best Answer

Why not simply use GUIDE instead of trying to build all this complicated stuff manually? Then, in the push button callback you'd simply do
listBoxItems = handles.input_list.Strings;
listBoxSelectedIndexes = handles.input_list.Value;
selectedString = listBoxItems{listBoxSelectedIndexes}
Related Question