| MATLAB® | ![]() |
| On this page… |
|---|
This example uses a list box to display the files in a directory. When the user double clicks on 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 directory, the GUI reads the contents of that directory into the list box.
If the item is a single dot (.), the GUI updates the display of the current directory.
If the item is two dots (..), the GUI changes to the directory up one level and populates the list box with the contents of that directory.
The following figure illustrates the GUI.

If you are reading this in the MATLAB® Help browser, you can click the following links to display the GUIDE Layout Editor and the MATLAB Editor with a completed version of this example. This enables you to see the values of all component properties and to understand how the components are assembled to create the GUI. You can also see a complete listing of the code that is discussed in the following sections.
Note The following links execute MATLAB commands and are designed to work within the MATLAB Help browser. If you are reading this online or in PDF, you should go to the corresponding section in the MATLAB Help Browser to use the links. |
The following sections describe the implementation:
Specifying the Directory to List — shows how to pass a directory path as input argument when the GUI is run.
Loading the List Box — describes the subfunction that loads the contents of the directory into the list box. This subfunction also saves information about the contents of a directory in the handles structure.
The List Box Callback — explains how the list box is programmed to respond to user double clicks on items in the list box.
You can specify the directory to list when the GUI is first opened by passing the string 'create' and a string containing the full path to the directory as arguments. The syntax for doing this is list_box('create','dir_path'). If you do not specify a directory (i.e., if you call the GUI M-file with no input arguments), the GUI then uses the MATLAB current directory.
The default behavior of the GUI M-file that GUIDE generates is to run the GUI when there are no input arguments or to call a subfunction when the first input argument is a character string. This example changes this behavior so that you can call the M-file with
No input arguments — run the GUI using the MATLAB current directory.
First input argument is 'dir' and second input argument is a string that specifies a valid path to a directory — run the GUI, displaying the specified directory.
First input argument is not a directory, but is a character string and there is more than one argument — execute the subfunction identified by the argument (execute callback).
The following code listing show the setup section of the GUI M-file, which does one the following:
Sets the list box directory to the current directory, if no directory is specified.
Changes the current directory, if a directory 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',...
'directory'},'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 creates a subfunction to load items into the list box. This subfunction accepts the path to a directory and the handles structure as input arguments. It performs these steps:
Change to the specified directory so the GUI can navigate up and down the tree as required.
Use the dir command to get a list of files in the specified directory and to determine which name is a directory 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 directory names (sortrows) and save the sorted names and other information in the handles structure so 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 directory names and set the Value property to 1. This is necessary to ensure Value never exceeds the number of items in String, since MATLAB software updates the Value property only when a selection occurs and not when the contents of String changes.
Displays the current directory 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 of the GUI M-file 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 on 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 directory, the GUI changes to that directory and lists its contents.
The callback makes use of the fact that the open command can handle a number of different file types. However, the callback treats FIG-files differently. Instead of opening the FIG-file, it passes it to the guide command for editing.
Since a single click on an item also invokes the list box callback, it is necessary to query the figure SelectionType property to determine when the user has performed a double click. A double-click on an item sets the SelectionType property to open.
All the items in the list box are referenced by an index from 1 to n, where 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.
The load_listbox function uses the dir command to obtain a list of values that indicate whether an item is a file or directory. These values (1 for directory, 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 directory and takes the following action:
If the selection is a directory — change to the directory (cd) and call load_listbox again to populate the list box with the contents of the new directory.
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 (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 directory
if handles.is_dir(handles.sorted_index(index_selected))
cd (filename)
% Load list box with new directory.
load_listbox(pwd,handles)
else
[path,name,ext,ver] = 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
errordlg(lasterr,'File Type Error','modal')
end
end
end
endYou can extend the file types that the open command recognizes to include any file having a three-character extension. You do this by creating an M-file with the name openxyz, where xyz is the extension. Note that the list box callback does not take this approach for FIG-files since openfig.m is required by the GUI M-file. See open for more information.
![]() | GUI with Multiple Axes | Accessing Workspace Variables from a List Box | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |