Products & Services Solutions Academia Support User Community Company

Learn more about MATLAB   

A GUI That Manages List Data

About the List Master Example

This GUI, called List Master, lets its users manage multiple lists such as to-do and shopping lists, cell phone numbers, catalogs of music or video recordings, or any set of itemizations. It has the following features:

A File menu handles creating, opening, and saving GUIs, and importing and exporting list data. The following figure displays the File menu of a new, unpopulated, List Master GUI on the left. On the right is a sample GUI it created, showing imported text data.

An empty List Master GUI

A List Master GUI with Controls and Data

The Components

A new List Master GUI figure contains a File menu, containing items to open or create a List Master GUI, import and export data, save the GUI and close it, as shown on the left side of the preceding illustration. Menu items are enabled and disabled as appropriate.

After you specify a new list's title, the GUI adds the following components:

The list box always has one and only one list item selected. A copy of that item appears in the edit box. If the user alters it in the edit box and presses Return, the edited text either replaces the current list selection or appears inserted after it. The state of the Replace and Add radio buttons controls where the GUI inserts the edited item. When the user saves a List Master GUI, its entire list is saved with it. The GUI prompts the user to save it before quitting if the list it contains has been modified.

Techniques Explored in the List Master Example

The example shows you how to

Viewing and Running the List Master GUI M-File

The List Master example includes an M-file, two MAT-files and a text file:

List Master looks for the listmaster_icons.mat MAT-file when creating a new GUI (from File > New menu). The files senators110cong.mat and senators110th.txt are not required to create or operate a GUI; you can use either one to populate a new List Master GUI with data using File > import list.

If you are reading this in the MATLAB Help browser, you can access the example M-files by clicking the following links. If you are reading this on the Web or in PDF form, you should 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, you should first save a copy of its M-file in your current folder (You need write access to your current folder to do this.) Click on the following links to copy the example files to your current folder and open them.

  1. Click here to copy the four files for List Master to your current folder

  2. edit listmaster or Click here to open the GUI M-file in the Editor

  3. edit senators110th.txt or Click here to display the senators110th.txt sample data file in the MATLAB Editor.

If you just want to run the GUI and inspect its code, follow these steps:

  1. Click here to add the example files to the MATLAB path (only for the current session).

  2. Click here to run the listmaster GUI.

  3. edit listmaster.m or Click here to display the GUI M-file in the MATLAB Editor (read-only).

  4. edit senators110th.txt or Click here to display the senators110th.txt sample data file in the MATLAB Editor.

Using List Master

A List Master GUI can create new instances of itself with File > New at any time, and any number of these instances can be open at the same time.

Starting List Master

To start using List Master, make sure listmaster.m is on your path, and run the main function.

  1. >> listmaster
    
    ans =
         1

    The function opens a blank GUI with the title ListMaster and a File menu and returns its figure handle.

  2. Select New from the File menu to set up the GUI to handle list data.

    The GUI presents a dialog box (using inputdlg).

  3. Type a name for the list you want to create and click OK.

    If you want to use the sample data provided with this example, you can call the list something like US Senate Phone Book, as shown on the left side of the following figure. (List Master restricts list names to 32 characters or fewer).

The New menu item's callback, lmnew, labels the figure and creates the GUI's controls, beginning with a uipanel. The panel encloses all the rest of the controls, resulting in a GUI as shown below on the right, with its controls labeled:

Creating a New List Master GUI

List Master Controls

Because the positions of all controls are specified with normalized Units, the GUI is resizable; only the button icons and the text fonts are of fixed size.

Importing Data into List Master

You can import data into a List Master GUI at any time. If the GUI already contains data, the data you import replaces it.

You can import into the GUI text from a cell array in the MATLAB workspace. Each element of the cell array should contain a line of text corresponding to a single list item. For example, you could define a list of grocery items as follows:

groceries = {'1 dozen large eggs';
             '1/2 gallon milk';
             '5 lb whole wheat flour';
             '1 qt. vanilla ice cream';};

If you load the example MAT-file senators110cong.mat and display it in the Variable Editor, you can see it is structured this way. Click here to load this MAT-file and open it in the Variable Editor.

Only use spaces as separators between words in lists. If a list contains tab characters, the list box does not display them, not even as blanks.

As it exists, you cannot import data from a text file using the List Master example M-file. It does contain a commented-out File menu item for this purpose and a callback for it (lmfileimport) containing no code. See Adding an "Import from File" Option to List Master for more information.

You do not need to import data to work with List Master. The GUI allows you to create lists by selecting the Add radio button, typing items in the edit text box one at a time, and pressing Return to add each one to the list. You can export any list you create.

Exporting Data from List Master

You can use File > Export list > to workspace to save the current list to a cell array in the MATLAB workspace. The lmwsexport callback performs this operation, calling the assignin function to create the variable after you specify its name. If you only want to export a single list item, you can use the system clipboard, as follows:

  1. Click on the list box item you want to copy or select the item's text in the edit box.

  2. Type Ctrl+C to copy the item.

  3. Open a document into which you want to paste the item

  4. Place the cursor where you want to paste the item and type Ctrl+V.

    The item appears in the external document.

You can also copy a string from another document and paste into the text edit box. (However, all Return and Tab characters the string might have are lost.)

You cannot paste from the system clipboard into the list box, because the content of a list box can only be changed programmatically, by setting its String property. This means that to paste new items into a list, you must add them one at a time via the edit text box. It also means you cannot copy the entire list and then paste it into another document.

You can save the entire contents of a list to a text file using File > Export list > to file. That menu item's callback (lmfileexport) opens a standard file dialog to navigate to a folder and specify a file name, then calls fopen, fprintf, and fclose to create, write, and close the file.

Saving the GUI

You do not need to export a list to save it. The Save and Save as menu options save lists by saving the entire GUI. They call the MATLAB saveas function to write the figure and all its contents as a FIG-file to disk. You can reopen the saved GUI by double-clicking it in the Current Folder browser, or by invoking hgload('figfilename.fig') from the Command Line. For the GUI to operate, however, listmaster.m must be in the current folder or elsewhere on the MATLAB path.

Programming List Master

The List Master GUI M-file contains 22 functions, organized into five groups.

List Master Main Program

The main function, listmaster, opens a figure in portrait format near the center of the screen. It then calls subfunction lm_make_file_menu to create a File menu. The following table describes the menu items and lists their callbacks. Click any function name in the Callback column to view it in the MATLAB Editor. Click any callback to view it in the MATLAB Editor. These links, as well as previous and subsequent links to List Master functions and callbacks, display the M-file in the Creating Graphical Interfaces examples folder, even if you have already copied it to your working folder.

Menu ItemHow UsedCallback
Open...Opens an existing List Master figurelmopen
New...Creates a List Master by adding controls to the initial GUI or to a new figure if the existing one already contains a listlmnew
Import list...Loads list data from a workspace cell arraylmwsimport
Export list...Generates a workspace cell array or text file containing the current listlmwsexport, lmfileexport
SaveSaves current List Master and its contents as a FIG-filelmsave
Save as...Saves current List Master to a different FIG-filelmsaveas
QuitExits List Master, with option to save firstlmquit

After you create a blank GUI with its File menu, the listmaster function exits.

The main function sets up the figure as follows:

fh = figure('MenuBar','none', ...
        'NumberTitle','off', ...
               'Name','ListMaster', ...
                'Tag','lmfigtag', ...
    'CloseRequestFcn', @lmquit, ...
              'Units','pixels', ...
           'Position', pos);

Turning off the MenuBar eliminates the default figure window menus, which the program later replaces with its own File menu. NumberTitle is turned off to eliminate a figure serial number in its title bar, which is given the title ListMaster via the Name property.

The initial Position of the GUI on the monitor is computed as follows:

su = get(0,'Units');
set(0,'Units','pixels')
scnsize = get(0,'ScreenSize');
scnsize(3) = min(scnsize(3),1280);  % Limit superwide screens
figx = 264; figy = 356;             % Default (resizable) GUI size
pos = [scnsize(3)/2-figx/2 scnsize(4)/2-figy/2 figx figy];
...
set(0,'Units',su)       % Restore default root screen units

The Open menu option only opens figures created by listmaster.m. Every List Master figure has its Tag set to lmfigtag. When the program opens a FIG-file, it uses this property value to determine that figure is a List Master GUI. If the Tag has any other value, the program closes the figure and displays an error alert.

The Quit menu option closes the GUI after checking whether the figure needs to be saved. If the contents have changed, its callback (lmquit) calls the lmsaveas callback to give the user an opportunity to save. The figure's CloseRequestFcn also uses the lmquit callback when the user clicks the figure's close box.

List Master Setup Functions

Although the initial GUI has no controls other than a menu, users can use File > Save as to save a blank GUI as a FIG-file. Opening the saved FIG-file has the same result as executing the listmaster function itself, assuming that listmaster.m is currently on the user's path.

Usually, however, users want to create a list, which they accomplish by clicking File > New. This executes setup functions that populate the GUI with uicontrols. The lmnew callback manages these tasks, calling setup functions in the following sequence. The three setup functions are listed and described below. Click any callback to view it in the MATLAB Editor. The function opens from the Creating Graphical Interfaces examples folder.

Setup FunctionHow Used
lm_get_list_nameCalls inputdlg to get name for new list, enforcing size limit of 32 characters
lm_make_ctrl_btnsCreates three push buttons for list navigation and a check box to control line numbering, loads listmaster_icons.mat, applies icons to push buttons as CData, and sets controls' callbacks
lm_make_edit_panelCreates button group with two radio buttons controlling editing mode, places a one-line text edit box below them, and sets callbacks for edit text control

lmnew then calls enable_updown, which is the callback for the list box (tagged lmtablisttag1). It is also called by all other functions that modify the list. The enable_updown subfunction sets the Enable property of the pair of push buttons that migrate items higher or lower in the list box. It disables the Move Up button when the selected item is at the top of the list, and disables the Move Down button when the selected item is at the bottom of the list. Then it copies the current list selection into the edit text box, replacing whatever was there. Finally, it sets the "dirty" flag in the figure's application data to indicate that the GUI's data or state has changed. See List Master Utility Functions for details.

Finally, having set up the GUI to receive data, lmnew enables the File > Import list menu option and its subitem.

List Master Menu Callbacks

List Master has seven menu items and three submenu items. A fourth submenu item, Import list from file, exists only as a stub provided as an exercise for the reader to implement. The menu items and their callbacks are listed in the table in the section List Master Main Program.

To obtain user input, the menu callbacks call built-in MATLAB GUI functions. Those used are

All are modal dialogs.

The New menu item has two modes of operation, depending on whether the GUI is blank or already contains a list box and associated controls. The lmnew callback determines which is the case by parsing the figure's Name property:

Called from a blank GUI, the function requests a name, and then populates the figure with all controls. Called from a GUI that contains a list, lmnew calls the main listmaster function to create a new GUI, and uses that figure's handle (instead of its own) when populating it with controls.

List Master List Callbacks

The six callbacks not associated with menu items are listed and described below. Click any callback to view it in the MATLAB Editor. The function opens from the Creating Graphical Interfaces examples folder.

Calback FunctionHow Used
move_list_itemCalled by the Move Up and Move Down push buttons to nudge items up and down list
enable_updownCalled from various subfunctions to enable and disable the Move Up and Move Down buttons and to keep the edit text box and list box synchronized.
delete_list_itemCalled from the Delete button to remove the currently selected item from the list; it keeps it in the edit text box in case the user decides to restore it.
enter_editA KeypressFcn called by the edit text box when user types a character; it sets the application data Edit flag when the user types Return.
commit_editA Callback called by the edit text box when user types Return or clicks elsewhere; it checks the application data Edit flag set by enter_edit and commits the edit text to the list only if Return was the last key pressed. This avoids committing edits inadvertently.
toggle_list_numbersCallback for the lmnumlistbtn check box, which prefixes line numbers to list items or removes them, depending on value of the check box

Identifying Component Handles.   A common characteristic of these and other List Master subfunctions is their way of obtaining handles for components. Rather than using the guidata function, which many GUIs use to share handles and other data for components, these subfunctions get handles they need dynamically by looking them up from their Tags, which are hard-coded and never vary. The code that finds handles uses the following pattern:

% Get the figure handle and from that, the listbox handle
fh = ancestor(hObject,'figure'); 
lh = findobj(fh,'Tag','lmtablisttag1');

Here, hObject is whatever object issued the callback that is currently executing, and 'lmtablisttag1' is the hard-coded Tag property of the list box. Always looking up the figure handle with ancestor assures that the current List Master is identified. Likewise, specifying the figure handle to findobj assures that only one list box handle is returned, regardless of how many List Master instances are open at the same time.

List Master Utility Functions

Certain callbacks rely on four small utility functions that are listed and described below. Click any callback to view it in the MATLAB Editor. The function opens from the Creating Graphical Interfaces examples folder.

Utility FunctionHow Used
number_listCalled to generate line numbers whenever a list updates and line numbering is on
guidirtySets the Boolean dirty flag in the figure's application data to true or false to indicate difference from saved version
isguidirtyReturns logical state of the figure's dirty flag
make_list_output_nameConverts the name of a list (obtained from the figure Name property) into a valid MATLAB identifier, which serves as a default when saving the GUI or exporting its data

List numbering works by adding five spaces before each list entry, then substituting numerals for characters 3, 2, and 1 of these blanks (as needed to display the digits) and placing a period in character 4. The numbers are stripped off the copy of the current item that displays in the text edit box, and then prepended again when the edit is committed (if the Number list check box is selected). This limits the size of lists that can be numbered to 999 items. You can modify number_list to add characters to the number field if you want the GUI to number lists longer than that.

The guidirty function sets the figure's application data using setappdata to indicate that it has been modified, as follows:

function guidirty(fh,yes_no)
% Sets the "Dirty" flag of the figure to true or false

setappdata(fh,'Dirty',yes_no);
% Also disable or enable the File->Save item according to yes_no
saveitem = findobj(fh,'Label','Save');
if yes_no
    set(saveitem,'Enable','on')
else
    set(saveitem,'Enable','off')
end

The isguidirty function queries the application data with getappdata to determine whether the figure needs to be saved in response to closing the GUI.

Adding an "Import from File" Option to List Master

If you want to round out List Master's capabilities, try activating the File > Import list > from file menu item. You can add this feature yourself by removing comments from lines 106-108 (enabling a File > Import list > from file menu item) and adding your own code to the callback. For related code that you can use as a starting point, see the lmfileexport callback for File > Export list > to file.

Adding a "Rename List" Option to List Master

When you import data to a list, you replace the entire contents of the list with the imported text. If the content of the new list is very different, you might want to give a new name to the list. (The list name appears above the list box). Consider adding a menu item or context menu item, such as Rename list. The callback for this item could

After renaming the list, the user can save the GUI to a new FIG-file with Save as. If the GUI had been saved previously, saving it to a new file preserves that version of the GUI with its original name and contents.

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS