| Contents | Index |
| On this page… |
|---|
About the List Box Directory Example |
This example uses a list box to display the files in a folder. When the user double clicks a list item, one of the following happens:
If the item is a file, the GUI opens the file appropriately for the file type.
If the item is a folder, the GUI reads the contents of that folder into the list box.
If the item is a single dot (.), the GUI updates the display of the current folder.
If the item is two dots (..), the GUI changes to the parent folder (one level up) and populates the list box with the contents of that folder.
The following figure illustrates the GUI.

If you are reading this document in the MATLAB Help browser, you can access the example FIG-file and code file by clicking the following links. If you are reading this on the Web or in PDF form, go to the corresponding section in the MATLAB Help Browser to use the links.
If you intend to modify the layout or code of this GUI example, first save a copy of its code file and FIG-file to your current folder (You need write access to your current folder to do this.) Follow these steps to copy the example files to your current folder and then to open them:
Type guide lbox2 or click here to open the FIG-file in GUIDE
Type edit lbox2 or click here to open the code file in the Editor
You can view the properties of any component by double-clicking it in the Layout Editor to open the Property Inspector for it. You can modify either the figure, the code, or both, and then save the GUI in your current folder using File > Save as from GUIDE. This saves both files, allowing you to rename them, if you choose.
To just inspect the GUI in GUIDE and run it, follow these steps instead:
Click here to add the example files to the MATLAB path (only for the current session).
Click here to display the GUI in the GUIDE Layout Editor (read only).
Click here to display the GUI code file in the MATLAB Editor (read only).
Note Do not save GUI files to the examples folder where you found them or you will overwrite the original files. If you want to save GUI files, use File > Save as from GUIDE, which saves both the GUI FIG-file and the GUI code file. |
The following sections describe the implementation:
Specify the Directory — shows how to pass a folder path as input argument when the GUI runs.
Load the List Box — describes the subfunction that loads the contents of the folder into the list box. This subfunction also saves information about the contents of a folder in the handles structure.
The List Box Callback — describes how the list box is programmed to respond to user double clicks on items in the list box.
By default, GUI code files generated by GUIDE open the GUI when there are no input arguments, and call a subfunction when the first input argument is a character string. This example changes the behavior so that if you put the example files, lbox2.m and lbox2.fig, on the MATLAB path you can run the GUI displaying a particular folder. To do so, pass the dir function as a string for the first input argument, and a string that specifies the path to the folder for the second input argument. For instance, from the Command Window, run the following to have the list box display the files in C:\myfiles:
lbox2('dir','C:\my_files')The following listing from lbox2.m shows the code for GUI initialization, which sets the list box folder to:
The current folder, if no folder is specified.
The specified folder, if a folder is specified.
function lbox2_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to untitled (see VARARGIN)
% Choose default command line output for lbox2
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
if nargin == 3,
initial_dir = pwd;
elseif nargin > 4
if strcmpi(varargin{1},'dir')
if exist(varargin{2},'dir')
initial_dir = varargin{2};
else
errordlg({'Input argument must be a valid',...
'folder'},'Input Argument Error!')
return
end
else
errordlg('Unrecognized input argument',...
'Input Argument Error!');
return;
end
end
% Populate the listbox
load_listbox(initial_dir,handles)This example uses a subfunction to load items into the list box. This subfunction accepts the path to a folder and the handles structure as input arguments and performs these steps:
Change to the specified folder so that the GUI can navigate up and down the tree, as required.
Use the dir command to get a list of files in the specified folder and to determine which name is a folder and which is a file. dir returns a structure (dir_struct) with two fields, name and isdir, which contain this information.
Sort the file and folder names (sortrows) and save the sorted names and other information in the handles structure so that this information can be passed to other functions.
The name structure field is passed to sortrows as a cell array, which is transposed to get one file name per row. The isdir field and the sorted index values, sorted_index, are saved as vectors in the handles structure.
Call guidata to save the handles structure.
Set the list box String property to display the file and folder names and set the Value property to 1, ensuring that Value never exceeds the number of items in String, because MATLAB software updates the Value property only when a selection occurs; not when the contents of String changes.
Displays the current folder in the text box by setting its String property to the output of the pwd command.
The load_listbox function is called by the opening function, as well as by the list box callback.
function load_listbox(dir_path, handles)
cd (dir_path)
dir_struct = dir(dir_path);
[sorted_names,sorted_index] = sortrows({dir_struct.name}');
handles.file_names = sorted_names;
handles.is_dir = [dir_struct.isdir];
handles.sorted_index = sorted_index;
guidata(handles.figure1,handles)
set(handles.listbox1,'String',handles.file_names,...
'Value',1)
set(handles.text1,'String',pwd)The list box callback handles only one case: a double-click of an item. Double clicking is the standard way to open a file from a list box. If the selected item is a file, it is passed to the open command; if it is a folder, the GUI changes to that folder and lists its contents.
Define How to Open File Types. The open command can handle a number of different file types, however, the callback treats FIG-files differently. Instead of opening the FIG-file as a standalone figure, it opens it with guide for editing.
Determine Which Item the User Selected. Since a single click of an item also invokes the list box callback, you must query the figure SelectionType property to determine when the user has performed a double click. A double-click of an item sets the SelectionType property to open.
All the items in the list box are referenced by an index from 1 to n. 1 refers to the first item and n is the index of the nth item. The software saves this index in the list box Value property.
The callback uses this index to get the name of the selected item from the list of items contained in the String property.
Determine Whether the Selected Item is a File or Directory. The load_listbox function uses the dir command to obtain a list of values that indicate whether an item is a file or folder. These values (1 for folder, 0 for file) are saved in the handles structure. The list box callback queries these values to determine if current selection is a file or folder and takes the following action:
If the selection is a folder — change to the folder (cd) and call load_listbox again to populate the list box with the contents of the new folder.
If the selection is a file — get the file extension (fileparts) to determine if it is a FIG-file, which is opened with guide. All other file types are passed to open.
The open statement is called within a try/catch block to capture errors in an error dialog box (errordlg), instead of returning to the command line.
get(handles.figure1,'SelectionType');
% If double click
if strcmp(get(handles.figure1,'SelectionType'),'open')
index_selected = get(handles.listbox1,'Value');
file_list = get(handles.listbox1,'String');
% Item selected in list box
filename = file_list{index_selected};
% If folder
if handles.is_dir(handles.sorted_index(index_selected))
cd (filename)
% Load list box with new folder.
load_listbox(pwd,handles)
else
[path,name,ext] = fileparts(filename);
switch ext
case '.fig'
% Open FIG-file with guide command.
guide (filename)
otherwise
try
% Use open for other file types.
open(filename)
catch ex
errordlg(...
ex.getReport('basic'),'File Type Error','modal')
end
end
end
endOpen Unknown File Types. You can extend the file types that the open command recognizes to include any file having a three-character extension. Do this by creating a MATLAB code file with the name openxyz.m. xyz is the file extension for the type of files to be handled. Do not, however, take this approach for opening FIG-files, because openfig.m is a MATLAB function which is needed to open GUIs. For more information, see open and openfig.
![]() | GUI to Interactively Explore Data in a Table (GUIDE) | Access Workspace Variables from a List Box (GUIDE) | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |