How to insert newline into displayed text in GUI?

조회 수: 24 (최근 30일)
Alexei
Alexei 2014년 11월 21일
댓글: Bogdan Dzyubak 2017년 6월 9일
I have a text box in my GUIDE-generated GUI in which I want to display the file that I just loaded (and read data from). I want it so that on the top line is just a file name, and on the next line it shows the path. I can't figure out how to insert a newline character into the string that I want to display. Somewhere on a forum site (perhaps this one) I saw someone suggest using the sprintf function like this:
string = sprintf([filename, '\n', pathname]);
set(handles.textbox,'String',string)
This WOULD work if only my filename and pathname did not have all sorts of special characters like underscores and backslashes. I tried escaping them by using the strrep function and replacing all underscores ---> '\_' and likewise any backslash ---> '\\'. Then I tried to do
string = sprintf([filename2, '\n', pathname2]);
where filename2 and pathname2 have been processed with strrep . But it fails to work! I continue to get an error when I try to run the GUI and display the loaded file into the textbox:
Warning: Escape sequence '_' is not valid. See 'help sprintf' for valid escape sequences.
Any suggestions? Why is sprintf still screwing up with the underscore if I escaped it?

답변 (2개)

Image Analyst
Image Analyst 2014년 11월 21일
string = sprintf('%s\n%s', filename2, pathname2);
set(handles.text1, 'String', string);

Jasper van Casteren
Jasper van Casteren 2017년 5월 15일
You need to initialize the textbox with a cell of strings. like
uicontrol(parent,'Style','text','String',{'Ready'}, 'tag', 'btTXT', . . .
then you can add lines by simple
h = guihandles(hObject)
h.btTXT.String = [h.btTXT.String; 'START'];
h.btTXT.String = [h.btTXT.String; sprintf('whatever you like = %d', whatever)];
  댓글 수: 1
Bogdan Dzyubak
Bogdan Dzyubak 2017년 6월 9일
Wow, super neat.
MyBox = uicontrol('style','text','FontSize',20);
set(MyBox,'Units','normalized','Position',[xpos,ypos,xsize,ysize]);
% set(MyBox,'String',['Get good ', ':-)']); % Single line
set(MyBox,'String',{'Get good, ', ':-)'}); % Double line!
Does not appear to be required, but someone else had commented that using set(MyBox,'Max',2) increases number of allowed lines from 1 to 2.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by