在Matlab GUIDE的列表框中插入一个新行

时间:2013-08-13 01:59:24

标签: matlab user-interface listbox matlab-guide

我正在使用GUIDE构建一个GUI,我有一个列表框,我想在点击send_button后收到几条消息,但每次点击按钮时,消息都显示在第一行。

function send_button_Callback(hObject, eventdata, handles)
% hObject    handle to send_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)  

  % get text
  dstID = get(handles.dest_ID,'String');
  msg = get(handles.message_box,'String');    % message_box = editbox

  % Build message and send
  msg = {['< ', dstID, ' >     ', msg]};      % dstID = number
  set(handles.message_list, 'String', msg);   % message_list = listbox

我应该怎么做才能拥有像

这样的东西
<3> Message one
<3> Message two
<3> Message three

我认为这是因为msg是一个字符串,但我不知道如何插入'\n'或类似的内容。

3 个答案:

答案 0 :(得分:2)

您可以使用get(handles.message_list,'string')获取包含列表框项目的字符串的单元格数组。这是解决问题的方法。

function send_button_Callback(hObject, eventdata, handles)
% hObject    handle to send_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)  

% get text
dstID = get(handles.dest_ID,'String');
msg = get(handles.message_box,'String');    % message_box = editbox

%get lisbox cell array of strings
cell_listbox = get(handles.message_list,'string');
%length is needed in order to append the desired message at the end
length_cell_listbox = length(cell_listbox);

% Build message and send
msg = ['< ', dstID, ' >     ', msg];      % dstID = number
cell_listbox{length_cell_listbox + 1} = msg;
set(handles.message_list, 'String', cell_listbox);   % message_list = listbox

使用相同的想法,您甚至可以创建一个按钮来删除列表框中存储的最后一条消息。

答案 1 :(得分:0)

试试这个:

...
msg=get(handles.message_box,'String');    % message_box = editbox
...
cell_listbox = get(handles.message_list,'string');
...
cell_listbox(end+1)=msg;

如果您收到错误,请提供它出现的行:)

答案 2 :(得分:0)

如果要将新邮件附加到顶部,则需要一个以新邮件开头的单元格数组。如果您的邮件太长,请重新塑造它们。请注意,在以下示例中,如果dstID大于9,则第一行可能太长,您可能需要更正maxlinelength来解释该问题。

maxlinelength = 25; %// maximum number of characters per line -5
current = get(handles.message_list,'string');

msg = get(handles.message_box,'String');    %// message_box = editbox
rows = ceil(length(msg)/maxlinelength);
msg = [char(8,8,8,8)' '< ' dstID ' > ' msg]; %'// append dstID display
newmsg = cell(1,rows);
for i=1:rows-1 %// for each row
    newmsg{i} = ['    ' a(1:maxlinelength)]; %// store the row in the new cell
    a = a(maxlinelength:end); %// cut off the row from the message
end
newmsg{rows} = ['    ' a]; %// last cell is the rest of msg

new = {msg,current{:}}; %// build new cell aray with msg at the front
set(handles.message_list, 'String', new);   %// message_list = listbox

如果您想要显示最多行数,也可以在设置为new之前切断'String'

if length(new)>maxlines
    new = new(1:maxlines);
end

char(8,8,8,8)'行将退格放在msg前面,以删除稍后添加的4个空格。如果您更改换行符缩进,请在此处更改8的数字。例如,如果您选择缩进2个空格,则会变为char(8,8)'