What is the best way to display a large text file

2020-02-29 10:53发布

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.

3条回答
forever°为你锁心
2楼-- · 2020-02-29 11:15

Here is my solution for a generic text file called "textfile.txt":

    f = figure('menu','none','toolbar','none');
    fid = fopen('textfile.txt');
    ph = uipanel(f,'Units','normalized','position',[0.4 0.3 0.5 0.5],'title',...
        'Display window');
    lbh = uicontrol(ph,'style','listbox','Units','normalized','position',...
        [0 0 1 1],'FontSize',9);

    indic = 1;
    while 1
         tline = fgetl(fid);
         if ~ischar(tline), 
             break
         end
         strings{indic}=tline; 
         indic = indic + 1;
    end
    fclose(fid);
    set(lbh,'string',strings);
    set(lbh,'Value',1);
    set(lbh,'Selected','on');
查看更多
疯言疯语
3楼-- · 2020-02-29 11:29

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

查看更多
▲ chillily
4楼-- · 2020-02-29 11:35

Here is my solution. Good Luck

fid = fopen(filename);
str = textscan(fid, '%s', 'Delimiter','\n'); str = str{1};
fclose(fid);
f=figure;
hPan = uipanel(f,'Units','normalized');
uicontrol(hPan, 'Style','listbox', ...
'HorizontalAlignment','left', ...
'Units','normalized', 'Position',[0 0 1 1], ...
'String',str);
查看更多
登录 后发表回答