| MATLAB® | ![]() |
| On this page… |
|---|
Programming User Interface Controls |
The examples assume that callback properties are specified using function handles, enabling MATLAB® software to pass arguments hObject, which is the handle of the component for which the event was triggered, and eventdata. See Associating Callbacks with Components for more information.
Note See Available Components for descriptions of these components. See Adding User Interface Controls for information about adding these components to your GUI. |
You can determine the current state of a check box from within any of its callbacks by querying the state of its Value property, as illustrated in the following example:
function checkbox1_Callback(hObject,eventdata) if (get(hObject,'Value') == get(hObject,'Max')) % Checkbox is checked-take approriate action else % Checkbox is not checked-take approriate action end
hObject is the handle of the component for which the event was triggered.
You can also change the state of a check box by programmatically by setting the check box Value property to the value of the Max or Min property. For example,
set(cbh,'Value','Max')
puts the check box with handle cbh in the checked state.
To obtain the string a user types in an edit box, use any of its callbacks to get the value of the String property. This example uses the Callback callback.
function edittext1_Callback(hObject,eventdata) user_string = get(hObject,'String'); % Proceed with callback
If the edit text Max and Min properties are set such that Max - Min > 1, the user can enter multiple lines. For example, setting Max to 2, with the default value of 0 for Min, enables users to enter multiple lines. If you originally specify String as a character string, multiline user input is returned as a 2-D character array with each row containing a line. If you originally specify String as a cell array, multiline user input is returned as a 2-D cell array of strings.
hObject is the handle of the component for which the event was triggered.
Retrieving Numeric Data from an Edit Text Component. MATLAB software returns the value of the edit text String property as a character string. If you want users to enter numeric values, you must convert the characters to numbers. You can do this using the str2double command, which converts strings to doubles. If the user enters nonnumeric characters, str2double returns NaN.
You can use code similar to the following in an edit text callback. It gets the value of the String property and converts it to a double. It then checks whether the converted value is NaN (isnan), indicating the user entered a nonnumeric character and displays an error dialog box (errordlg).
function edittext1_Callback(hObject,eventdata)
user_entry = str2double(get(hObject,'string'));
if isnan(user_entry)
errordlg('You must enter a numeric value','Bad Input','modal')
return
end
% Proceed with callback...Triggering Callback Execution. If the contents of the edit text component have been changed, clicking inside the GUI, but outside the edit text, causes the edit text callback to execute. The user can also press Enter for an edit text that allows only a single line of text, or Ctrl+Enter for an edit text that allows multiple lines.
Available Keyboard Accelerators. GUI users can use the following keyboard accelerators to modify the content of an edit text. These accelerators are not modifiable.
Ctrl+X – Cut
Ctrl+C – Copy
Ctrl+V – Paste
Ctrl+H – Delete last character
Ctrl+A – Select all
When the list box Callback callback is triggered, the list box Value property contains the index of the selected item, where 1 corresponds to the first item in the list. The String property contains the list as a cell array of strings.
This example retrieves the selected string. Note that it is necessary to convert the value of the String property from a cell array to a string.
function listbox1_Callback(hObject,eventdata)
index_selected = get(hObject,'Value');
list = get(hObject,'String');
item_selected = list{index_selected}; % Convert from cell array
% to stringhObject is the handle of the component for which the event was triggered.
You can also select a list item programmatically by setting the list box Value property to the index of the desired item. For example,
set(lbh,'Value',2)
selects the second item in the list box with handle lbh.
Triggering Callback Execution. MATLAB software executes the list box Callback callback after the mouse button is released or after certain key press events:
The arrow keys change the Value property, trigger callback execution, and set the figure SelectionType property to normal.
The Enter key and space bar do not change the Value property, but trigger callback execution and set the figure SelectionType property to open.
If the user double-clicks, the callback executes after each click. the software sets the figure SelectionType property to normal on the first click and to open on the second click. The callback can query the figure SelectionType property to determine if it was a single or double click.
List Box Examples. See the following examples for more information on using list boxes:
List Box Directory Reader — Shows how to creates a GUI that displays the contents of directories in a list box and enables users to open a variety of file types by double-clicking the filename.
Accessing Workspace Variables from a List Box — Shows how to access variables in the MATLAB base workspace from a list box GUI.
When the pop-up menu Callback callback is triggered, the pop-up menu Value property contains the index of the selected item, where 1 corresponds to the first item on the menu. The String property contains the menu items as a cell array of strings.
Note A pop-up menu is sometimes referred to as a drop-down menu or combo box. |
Using Only the Index of the Selected Menu Item. This example retrieves only the index of the item selected. It uses a switch statement to take action based on the value. If the contents of the pop-up menu are fixed, then you can use this approach. Else, you can use the index to retrieve the actual string for the selected item.
function popupmenu1_Callback(hObject,eventdata) val = get(hObject,'Value'); switch val case 1 % User selected the first item case 2 % User selected the second item % Proceed with callback...
hObject is the handle of the component for which the event was triggered.
You can also select a menu item programmatically by setting the pop-up menu Value property to the index of the desired item. For example,
set(pmh,'Value',2)
selects the second item in the pop-up menu with handle pmh.
Using the Index to Determine the Selected String. This example retrieves the actual string selected in the pop-up menu. It uses the pop-up menu Value property to index into the list of strings. This approach may be useful if your program dynamically loads the contents of the pop-up menu based on user action and you need to obtain the selected string. Note that it is necessary to convert the value returned by the String property from a cell array to a string.
function popupmenu1_Callback(hObject,eventdata)
val = get(hObject,'Value');
string_list = get(hObject,'String');
selected_string = string_list{val}; % Convert from cell array
% to string
% Proceed with callback...hObject is the handle of the component for which the event was triggered.
This example contains only a push button. Clicking the button, closes the GUI.

This is the push button's Callback callback. It displays the string Goodbye at the command line and then closes the GUI.
function pushbutton1_Callback(hObject,eventdata) display Goodbye close(gcbf)
gcbf returns the handle of the figure containing the object whose callback is executing.
You can determine the current state of a radio button from within its Callback callback by querying the state of its Value property, as illustrated in the following example:
function radiobutton_Callback(hObject,eventdata) if (get(hObject,'Value') == get(hObject,'Max')) % Radio button is selected-take approriate action else % Radio button is not selected-take approriate action end
Radio buttons set Value to Max when they are on (when selected) and Min when off (not selected). hObject is the handle of the component for which the event was triggered.
You can also change the state of a radio button programmatically by setting the radio button Value property to the value of the Max or Min property. For example,
set(rbh,'Value','Max')
puts the radio button with handle rbh in the selected state.
Note You can use a button group to manage exclusive selection behavior for radio buttons. See Button Group for more information. |
You can determine the current value of a slider from within its Callback callback by querying its Value property, as illustrated in the following example:
function slider1_Callback(hObject,eventdata) slider_value = get(hObject,'Value'); % Proceed with callback...
The Max and Min properties specify the slider's maximum and minimum values. The slider's range is Max - Min. hObject is the handle of the component for which the event was triggered.
The callback for a toggle button needs to query the toggle button to determine what state it is in. MATLAB software sets the Value property equal to the Max property when the toggle button is pressed (Max is 1 by default). It sets the Value property equal to the Min property when the toggle button is not pressed (Min is 0 by default).
The following code illustrates how to program the callback in the GUI M-file.
function togglebutton1_Callback(hObject,eventdata)
button_state = get(hObject,'Value');
if button_state == get(hObject,'Max')
% Toggle button is pressed-take approperiate action
...
elseif button_state == get(hObject,'Min')
% Toggle button is not pressed-take appropriate action
...
endhObject is the handle of the component for which the event was triggered.
You can also change the state of a toggle button programmatically by setting the toggle button Value property to the value of the Max or Min property. For example,
set(tbh,'Value','Max')
puts the toggle button with handle tbh in the pressed state.
Note You can use a button group to manage exclusive selection behavior for toggle buttons. See Button Group for more information. |
These topics provide basic code examples for panels and button group callbacks.
The examples assume that callback properties are specified using function handles, enabling MATLAB software to pass arguments hObject, which is the handle of the component for which the event was triggered, and eventdata. See Associating Callbacks with Components for more information.
Panels group GUI components and can make a GUI easier to understand by visually grouping related controls. A panel can contain panels and button groups, as well as axes and user interface controls such as push buttons, sliders, pop-up menus, etc. The position of each component within a panel is interpreted relative to the lower-left corner of the panel.
Generally, if the GUI is resized, the panel and its components are also resized. However, you can control the size and position of the panel and its components. You can do this by setting the GUI Resize property to on and providing a ResizeFcn callback for the panel.
Note See Cross-Platform Compatible Units for information about the effect of units on resize behavior. |
Button groups are like panels except that they manage exclusive selection behavior for radio buttons and toggle buttons. If a button group contains a set of radio buttons, toggle buttons, or both, the button group allows only one of them to be selected. When a user clicks a button, that button is selected and all other buttons are deselected.
The following figure shows a button group with two radio buttons and two toggle buttons. Radio Button 1 is selected.

If a user clicks the other radio button or one of the toggle buttons, it becomes selected and Radio Button 1 is deselected. The following figure shows the result of clicking Toggle Button 2.

The button group SelectionChangeFcn callback is called whenever a selection is made. If you have a button group that contains a set of radio buttons and toggle buttons and you want:
An immediate action to occur when a radio button or toggle button is selected, you must include the code to control the radio and toggle buttons in the button group's SelectionChangeFcn callback function, not in the individual toggle button Callback functions. Color Palette provides a practical example of a SelectionChangeFcn callback.
Another component such as a push button to base its action on the selection, then that component's Callback callback can get the handle of the selected radio button or toggle button from the button group's SelectedObject property.
This example of a SelectionChangeFcn callback uses the Tag property of the selected object to choose the appropriate code to execute. The Tag property of each component is a string that identifies that component and must be unique in the GUI.
function uibuttongroup1_SelectionChangeFcn(hObject,eventdata)
switch get(eventdata.NewValue,'Tag') % Get Tag of selected object.
case 'radiobutton1'
% Code for when radiobutton1 is selected.
case 'radiobutton2'
% Code for when radiobutton2 is selected.
case 'togglebutton1'
% Code for when togglebutton1 is selected.
case 'togglebutton2'
% Code for when togglebutton2 is selected.
% Continue with more cases as necessary.
otherwise
% Code for when there is no match.
endThe hObject and eventdata arguments are available to the callback only if the value of the callback property is specified as a function handle. See the SelectionChangeFcn property on the Uibuttongroup Properties reference page for information about eventdata. See the uibuttongroup reference page and Color Palette for other examples.
Axes components enable your GUI to display graphics, such as graphs and images. This topic briefly tells you how to plot to an axes in your GUI.
In most cases, you create a plot in an axes from a callback that belongs to some other component in the GUI. For example, pressing a button might trigger the plotting of a graph to an axes. In this case, the button's Callback callback contains the code that generates the plot.
The following example contains two axes and two push buttons. Clicking the first button generates a contour plot in one axes and clicking the other button generates a surf plot in the other axes. The example generates data for the plots using the peaks function, which returns a square matrix obtained by translating and scaling Gaussian distributions.
Save this code in an M-file named two_axes.m.
function two_axes
fh = figure;
bh1 = uicontrol(fh,'Position',[20 290 60 30],...
'String','Plot 1',...
'Callback',@button1_plot);
bh2 = uicontrol(fh,'Position',[20 100 60 30],...
'String','Plot 2',...
'Callback',@button2_plot);
ah1 = axes('Parent',fh,'units','pixels',...
'Position',[120 220 170 170]);
ah2 = axes('Parent',fh,'units','pixels',...
'Position',[120 30 170 170]);
%------------------------------------------------
function button1_plot(hObject,eventdata)
contour(ah1,peaks(35));
end
%------------------------------------------------
function button2_plot(hObject,eventdata)
surf(ah2,peaks(35));
end
endRun the GUI by typing two_axes at the command line. This is what the example looks like before you click the push buttons.

Click the Plot 1 button to display the contour plot in the first axes. Click the Plot 2 button to display the surf plot in the second axes.

See GUI with Multiple Axes for a more complex example that uses two axes.
If your GUI contains axes, you should ensure that their HandleVisibility properties are set to callback. This allows callbacks to change the contents of the axes and prevents command line operations from doing so. The default is on.
For more information about:
Properties that you can set to control many aspects of axes behavior and appearance, see Axes Properties in the MATLAB Graphics documentation.
Creating axes in a tiled pattern, see the subplot function reference page.
Plotting in general, see Plots and Plotting Tools in the MATLAB Graphics documentation.
For information about programming ActiveX® controls, see the following topics in the MATLAB External Interfaces documentation.
See Creating COM Objects in the MATLAB External Interfaces documentation for general information.
Because clicking a menu title automatically displays the menu below it, you may not need to program callbacks at the title level. However, the callback associated with a menu title can be a good place to enable or disable menu items below it.
Consider the example illustrated in the following picture.

When a user selects Edit > Copy > to file, no Copy callback is needed to perform the action. Only the Callback callback associated with the to file item is required.
Suppose, however, that only certain objects can be copied to a file. You can use the Copy item Callback callback to enable or disable the to file item, depending on the type of object selected.
The following code disables the to file item by setting its Enable property off. The menu item would then appear dimmed.
set(tofilehandle,'Enable','off')
Setting Enable to on, would then enable the menu item.
The Callback callback for the to file menu item could contain code such as the following to display the standard dialog box for saving files.
[file,path] = uiputfile('animinit.m','Save file name');'Save file name' is the dialog box title. In the dialog box, the filename field is set to animinit.m, and the filter set to M-files (*.m). For more information, see the uiputfile reference page.
Note MATLAB software provides a selection of standard dialog boxes that you can create with a single function call. For information about these dialog boxes and the functions used to create them, see Predefined Dialog Boxes in the MATLAB Function Reference documentation. |
A check is useful to indicate the current state of some menu items. If you set the Checked property to on when you create the menu item, the item initially appears checked. Each time the user selects the menu item, the callback for that item must turn the check on or off. The following example shows you how to do this by changing the value of the menu item's Checked property.
function menu_copyfile(hObject,eventdata)
if strcmp(get(hObject,'Checked'),'on')
set(hObject,'Checked','off');
else
set(hObject,'Checked','on');
endhObject is the handle of the component for which the event was triggered. Its use here assumes the menu item's Callback property specifies the callback as a function handle. See Associating Callbacks with Components for more information.
The strcmp function compares two strings and returns logical 1 (true) if the two are identical, and logical 0 (false) otherwise.
Use of checks when the GUI is first displayed should be consistent with the display. For example, if your GUI has an axes that is visible when a user first opens it and the GUI has a Show axes menu item, be sure to set the menu item's Checked property on when you create it so that a check appears next to the Show axes menu item initially.
The push tool ClickedCallback property specifies the push tool control action. The following example creates a push tool and programs it to open a standard color selection dialog box. You can use the dialog box to set the background color of the GUI.
Copy the following code into an M-file and save it in your current directory or on your path as color_gui.m. Run the script by typing color_gui at the command line.
function color_gui
fh = figure('Position',[250 250 250 150],'Toolbar','none');
th = uitoolbar('Parent',fh);
pth = uipushtool('Parent',th,'Cdata',rand(20,20,3),...
'ClickedCallback',@color_callback);
%-------------------------------------------------------
function color_callback(hObject,eventdata)
color = uisetcolor(fh,'Pick a color');
end
endClick the push tool to display the color selection dialog box and click a color to select it.

Click OK on the color selection dialog box. The GUI background color changes to the color you selected—in this case, green.

Note Create your own icon with the icon editor described in Icon Editor. See the ind2rgb reference page for information on converting a matrix X and corresponding colormap, i.e., an (X, MAP) image, to RGB (truecolor) format. |
The toggle tool OnCallback and OffCallback properties specify the toggle tool control actions that occur when the toggle tool is clicked and its State property changes to on or off. The toggle tool ClickedCallback property specifies a control action that takes place whenever the toggle tool is clicked, regardless of state.
The following example uses a toggle tool to toggle a plot between surface and mesh views of the peaks data. The example also counts the number of times you have clicked the toggle tool.
The surf function produces a 3-D shaded surface plot. The mesh function creates a wireframe parametric surface. peaks returns a square matrix obtained by translating and scaling Gaussian distributions
Copy the following code into an M-file and save it in your current directory or on your path as toggle_plots.m. Run the script by typing toggle_plots at the command line.
function toggle_plots
counter = 0;
fh = figure('Position',[250 250 300 340],'Toolbar','none');
ah = axes('Parent',fh,'Units','pixels',...
'Position',[35 85 230 230]);
th = uitoolbar('Parent',fh);
tth = uitoggletool('Parent',th,'Cdata',rand(20,20,3),...
'OnCallback',@surf_callback,...
'OffCallback',@mesh_callback,...
'ClickedCallback',@counter_callback);
sth = uicontrol('Style','text','String','Counter: ',...
'Position',[35 20 45 20]);
cth = uicontrol('Style','text','String',num2str(counter),...
'Position',[85 20 30 20]);
%-------------------------------------------------------
function counter_callback(hObject,eventdata)
counter = counter + 1;
set(cth,'String',num2str(counter))
end
%-------------------------------------------------------
function surf_callback(hObject,eventdata)
surf(ah,peaks(35));
end
%-------------------------------------------------------
function mesh_callback(hObject,eventdata)
mesh(ah,peaks(35));
end
end

Click the toggle tool to display the initial plot. The counter increments to 1.

Continue clicking the toggle tool to toggle between surf and mesh plots of the peaks data.
![]() | Callbacks: An Overview | Managing Application-Defined Data | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |