What is the best way to display a large text file in MATLAB GUIDE?

julianfperez picture julianfperez · Oct 27, 2011 · Viewed 7.8k times · Source

How can a MATLAB GUIDE control be used to display the contents of a text file in a GUI? The text file may be very long or very wide so it should have the ability to have vertical and horizontal scroll bars.

Answer

Amro picture Amro · Oct 28, 2011

A multi-line editbox may be the best choice to display the text. Example:

%# read text file lines as cell array of strings
fid = fopen( fullfile(matlabroot,'license.txt') );
str = textscan(fid, '%s', 'Delimiter','\n'); str = str{1};
fclose(fid);

%# GUI with multi-line editbox
hFig = figure('Menubar','none', 'Toolbar','none');
hPan = uipanel(hFig, 'Title','Display window', ...
    'Units','normalized', 'Position',[0.05 0.05 0.9 0.9]);
hEdit = uicontrol(hPan, 'Style','edit', 'FontSize',9, ...
    'Min',0, 'Max',2, 'HorizontalAlignment','left', ...
    'Units','normalized', 'Position',[0 0 1 1], ...
    'String',str);

%# enable horizontal scrolling
jEdit = findjobj(hEdit);
jEditbox = jEdit.getViewport().getComponent(0);
jEditbox.setWrapping(false);                %# turn off word-wrapping
jEditbox.setEditable(false);                %# non-editable
set(jEdit,'HorizontalScrollBarPolicy',30);  %# HORIZONTAL_SCROLLBAR_AS_NEEDED

%# maintain horizontal scrollbar policy which reverts back on component resize 
hjEdit = handle(jEdit,'CallbackProperties');
set(hjEdit, 'ComponentResizedCallback',...
    'set(gcbo,''HorizontalScrollBarPolicy'',30)')

To enable horizontal scrolling, we must get a handle to the embedded JScrollPane java component. I am using the excellent FINDJOBJ function. Then we set the HorizontalScrollBarPolicy property to javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED (= 30) as explained in this post. I also disabled editing of the text (read only).

screenshot