MATLAB Answers

0

How to Add Element/Item to Listbox in Matlab GUI (push button, listbox)

Asked by Thomas Côté on 17 Jun 2019
Latest activity Answered by Geoff Hayes
on 17 Jun 2019
Hi there, I'm trying to add new (and only new) elements to my initially empty GUI Listbox, but it just doesn't work out. Here's my code for the pushbutton callback :
function pushbutton2_Callback(hObject, eventdata, handles)
Items_2 = {};
handles = guidata(hObject);
folder = handles.folder;
pathname = folder;
Item_1 = handles.selectedItemStr; %Comes from another listbox.
guidata(hObject, handles)
while ~strcmpi(Items_2, Item_1) %When the Item_1 is allready in Items_2, the While Loop ends by itself and Items_2 stays the same.
Items_2 = [Item_1, Items_2]; % However, in the contrary, Item_1 is added to the Items_2 (cell arrays of string characters)
set(handles.listbox2,'String',Items_2); %Update the list in Listbox2.
break
end
Here's my code for the listbox 2 callback :
function listbox2_Callback(hObject, eventdata, handles)
%I don't think I need to do this, but I do it anyway.
list = get(handles,'String');
set(handles,'String',list);
When I run my GUI, it shows no error, but the list doesn't update nor doesn't add any new item.
Thanks for the help!

  0 Comments

Sign in to comment.

1 Answer

Answer by Geoff Hayes
on 17 Jun 2019
 Accepted Answer

Thomas - perhaps the condition
~strcmpi(Items_2, Item_1)
is never evaluating to true and so you never enter the body of the while loop. Part of the problem may be because Items_2 is always initialized to an empty cell array (is this intentional?) and is never set to what is currently in your list. Note that if I try the above, with
g = {};
strcmpi(g, 'hello')
then an empty array is returned...so I suspect that is the real problem. The condition is never satisfied. Try doing something like the following instead
function pushbutton2_Callback(hObject, eventdata, handles)
selectedString = handles.selectedItemStr; % assumed to be a string
listBox2Data = get(handles.listbox2,'String');
if isempty(listBox2Data) || ~any(strcmpi(listBox2Data, selectedString))
listBox2Data = [selectedString, listBox2Data];
set(handles.listbox2,'String',listBox2Data);
end
No need for a while loop in this case. Note that we use the call to any since the strcmpi may return an array of 0 or 1s for each element in the list box. any will return true if at least one of these elements is a one (indicating that the selected string is already in the list). If the call returns 0 (i.e. no element in list matches the selected string) then we add the item to the list.

  0 Comments

Sign in to comment.