How to Add Element/Item to Listbox in Matlab GUI (push button, listbox)
조회 수: 43 (최근 30일)
이전 댓글 표시
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
채택된 답변
Geoff Hayes
2019년 6월 17일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!