Skip to Main Content Skip to Search
Product Documentation

Compose and Code GUIs with Interactive Tools

Laying out a programmatic GUI can take time and involves many small steps. For example, you must position components manually—often several times—to place them exactly where you want them to be. Establishing final settings for other properties and coding statements for them also takes time. You can reduce the effort involved by taking advantage of built-in MATLAB tools and GUIs to establish values for component properties. The following sections describe some of the tools.

Mode or ToolUse it toCommands
Plot edit modeInteractively edit and annotate plotsplotedit
Property EditorEdit graphical properties of objectspropedit, propertyeditor
Property InspectorInteractively display and edit most object propertiesinspect
Align ToolAlign and distribute components with respect to one anotheralign
Color SelectorChoose a color from a palette of colors and obtain its valueuisetcolor
Font SelectorPreview character font, style, and size and choose values for themuisetfont

Some of these tools return property values, while others let you edit properties interactively without returning their values. In particular, the Property Inspector lets you interactively set almost any object property. You then can copy property values and paste them into the Command Window or a code file. However, when you capture vector-valued properties, such as Color or Position, the Inspector only lets you copy values one number at a time.

Set Positions of Components Interactively

If you do not like the initial positions or other properties of GUI components, you can make manual adjustments to them. By placing the GUI figure in plot edit mode, you can use your mouse to move, resize, align, and change various components properties. Then, you can read out values of properties you changed and copy them into your GUI code file to initialize the components.

To set position in plot edit mode:

  1. Enter plot edit mode. Click the Arrow tool , or select Edit Plot from the Tools menu. If your figure has no menus or toolbar, type plotedit on in the Command Window.

  2. Select a component. Click the left mouse button while over the component you are editing.

  3. Move and resize the component. Click within it and drag to move it to a new location. Click a square black handle and drag to change its shape. Use arrow keys to make small adjustments.

  4. Make sure that you know the handle of the component you have manipulated. In the following code, the handle is a variable named object_handle.

  5. Obtain the component position vector from the Property Inspector. Type

    inspect

    or enter a get statement, such as:

    get(object_handle, 'Position')
    ans =
       15.2500  333.0000  106.0000   20.0000
  6. Copy the result (ans) and insert it in a set statement in your code file, within square brackets:

    set(object_handle, 'Position', [15.2500 333.0000 106.0000 20.0000])
    

To position components systematically, you can create a function to manage the process. Here is a simple example function called editpos:

function rect = editpos(handle)
% Enters plot edit mode, pauses to let user manipulate objects,
% then turns the mode off. It does not track what user does.
% User later needs to output a Position property, if changed.

if ~ishghandle(handle)
    disp(['=E= gbt_moveobj: Invalid handle: ' inputname(1)])
    return
end
plotedit(handle,'on')
disp('=== Select, move and resize object. Use mouse and arrow keys.')
disp('=== When you are finished, press Return to continue.')
pause
rect = get(handle,'Position');
inspect(handle)

To experiment with the function, enter the following code in the Command Window:

hfig = figure; 
hsl = uicontrol('Style','slider') 
editpos(hsl) 

After you call editpos, the following prompt appears:

=== Select, move and resize the object. Use mouse and arrow keys. 
=== When you are finished, press Return to continue. 

When you first enter plot edit mode, the selection is figure itself. Click the slider to select it and reposition it. For example, move it to the right side of the figure and orient it vertically, as shown in the following figure.

Use Plot Edit Mode to Change Properties

After you select an object in plot edit mode, you can open the Property Inspector to view and modify any of its properties. While the object is selected, in the Command Window type:

inspect

You also can use the functional form to pass in the handle of the object you want to inspect, for example:

inspect(hsl)

The Property Inspector opens, displaying the object properties. You can edit as well as read property values, and the component updates immediately. To see a definition of any property, right-click the name or value in the Property Inspector and click the What's This? menu item that appears. A context-sensitive help window opens displaying the definition of the property, as shown in the next illustration.

Scroll in the help window to view descriptions of other properties. Click the X close box to close the window.

The following Inspector image illustrates using the Inspector to change the Max property of a slider uicontrol from its default value (1.0) to 10.0.

Edit with the Property Editor

The Property Editor has a more graphical interface than the Property Inspector. The interface is convenient for setting properties that affect the appearance of components. To open it for a component, in the Command Window type:

propedit(object_handle)

Alternatively, omit the argument and type:

plotedit on

The figure enters plot edit mode. Select the object you want to edit and change any property that the Property Editor displays. The following figure shows the BackgroundColor and String properties of a list box altered using the Property Editor.

Most of the properties that the Property Editor can set are cosmetic. To modify values for other properties, click More Properties. The Property Inspector opens (or, if already open, receives focus) to display properties of the selected object. Use it to change properties that the Property Editor does not display.

When you finish setting a property, you need to save its value:

You can obtain the new property value by running the get function:

value = get(object_handle, 'PropertyName')

Transfer the value to your GUI program file. Either include it as a parameter-value pair in the statement creating the object, or as a set command for it later in the file. For some tools and techniques that aid in programming properties, see Generate Code to Set Component Properties.

Sketch a Position Vector

rbbox is a useful function for setting positions. When you call it, you drag out a rubber band box anywhere in the figure. You receive a position vector for that box when you release the mouse button. Be aware that when rbbox executes,

Because of this behavior, you must call rbbox from a function or a script that waits for you to press the mouse button. The returned position vector specifies the rectangle you draw in figure units. The following function, called setpos, calls rbbox to specify a position for a component. It returns the position vector you drag out and also places it on the system clipboard:

function rect = setpos(object_handle)
% Use RBBOX to establish a position for a GUI component.
% object_handle is a handle to a uicomponent that uses
% any Units. Internally, figure Units are used.

disp(['=== Drag out a Position for object ' inputname(1)])
waitforbuttonpress  % So that rbbox does not return immediately
rect = rbbox;     % User drags out a rectangle, releases button
% Pressing a key aborts rbbox, so check for null width & height
if rect(3) ~= 0 && rect(4) ~= 0
    % Save and restore original units for object
    myunits = get(object_handle,'Units');
    set(object_handle,'Units',get(gcf,'Units'))
    set(object_handle,'Position',rect)
    set(object_handle,'Units',myunits)
else
    rect = [];
end
clipboard('copy', rect)         % Place set string on system
                                % clipboard as well as returning it

The setpos function uses figure units to set the component Position property. First, setpos gets and saves the Units property of the component, and sets that property to figure units. After setting the object position, the function restores the original units of the object.

The following steps show how to use setpos to reposition a button away from its default position:

  1. Put this statement into your GUI code file, and then execute it:

    btn1 = uicontrol('Style','pushbutton',...
    'String','Push Me');
    

  2. Put the following statement in your GUI code file, execute it, and then drag out a Position for object btn1.

    rect = setpos(btn1)
    

  3. Release the mouse button. The control moves.

  4. The button Position is set, returned and placed on the system clipboard:

    rect =
         37  362  127   27

    Add a Position parameter and empty value to the uicontrol command from step 1 in your GUI code file, as follows:

    btn1 = uicontrol('Style','pushbutton',...
    'String','Push Me','Position',[])

    With the cursor inside the brackets [], type Ctrl+V to paste the setpos output as the Position parameter value:

    btn1 = uicontrol('Style','pushbutton',...
    'String','Push Me','Position',[37  362  127   27])

You cannot call setpos when you are creating a component because setpos requires the handle of the component as an argument. However, you can create a small function that lets you position a component interactively as you create it. The function waits for you to press the mouse button, then calls rbbox, and returns a position rectangle when you release the mouse button:

function rect = getrect
disp('=== Click and drag out a Position rectangle.')
waitforbuttonpress  % So that rbbox does not return immediately
rect = rbbox;     % User drags out a rectangle, releases button
clipboard('copy', rect)            % Place set string on system
%                             clipboard as well as returning it

To use getrect:

  1. In the editor, place the following statement in your GUI code file to generate a push button. Specify getrect within it as the value for the Position property:

    btn1 = uicontrol('Style','pushbutton','String','Push Me',...
                     'Position',getrect);
  2. Select the entire statement in the editor and execute it with the F9 key or by right-clicking and selecting Evaluate Selection.

  3. In the figure window, drag out a rectangle for the control to occupy. When you have finished dragging, the new component displays in that rectangle. (If you type a character while you are dragging, rbbox aborts, you receive an error, and no uicontrol is created.)

  4. In the editor, select getrect in the uicontrol statement, and type [] in place of it. The statement now looks like this:

    btn1 = uicontrol('Style','pushbutton','String','Push Me',...
                     'Position',[]);
  5. Place your cursor between the empty brackets and type Ctrl+V, or right-click and select Paste. Allowing for differences in coordinate values, the statement looks like this one:

    btn1 = uicontrol('Style','pushbutton','String','Push Me',...
                     'Position',[55  253  65  25]);

Remember that rbbox returns coordinates in figure units ('pixels', in this example). If the default Units value of a component is not the same as the figure, specify it to be the same when you make the component. For example, the default Units of a uipanel is 'normalized'. To sketch a uipanel position, use code that uses figure Units, as in the following example:

pnl1 = uipanel('Title','Inputs',...
               'Units',get(gcf,'Units'),...
               'Position',getrect)

Two MATLAB utilities for composing GUIs can assist you in specifying positions. Use getpixelposition to obtain a position vector for a component in units of pixels regardless of its Units setting. The position origin is with respect to the parent of the component or the enclosing figure. Use setpixelposition to specify a new component position in pixels. The Units property of the component remains unchanged after calling either of these functions.

Align Components

After you position components, they still might not line up perfectly. To make final adjustments, use the align function from the Command Window. As an interactive alternative, use the Align Distribute tool, a GUI available from the figure menu. The following sections describe both approaches.

Use the align Function

Use the align function to align user interface controls and axes. This function enables you to line up the components vertically and horizontally. You can also distribute the components evenly across their span or specify a fixed distance between them.

A syntax for the align function is

align(HandleList,'HorizontalAlignment','VerticalAlignment')

The following table lists the possible values for these parameters.

HorizontalAlignmentVerticalAlignment
None, Left, Center, Right, Distribute, or FixedNone, Top, Middle, Bottom, Distribute, or Fixed

All handles in HandleList must have the same parent. See the align reference page for information about other syntaxes.

The align function positions components with respect to their bounding box, shown as a blue dashed line in the following figures. For demonstration purposes, create three push buttons in arbitrary places using the following code.

fh = figure('Position',[400 300 300 150])
b1 = uicontrol(fh,'Posit',[30 10 60 30],'String','Button 1');
b2 = uicontrol(fh,'Posit',[50 50 60 30],'String','Button 2');
b3 = uicontrol(fh,'Posit',[10 80 60 30],'String','Button 3');

Align Components Horizontally.   The following statement moves the push buttons horizontally to the right of their bounding box. It does not alter their vertical positions. The figure shows the original bounding box.

align([b1 b2 b3],'Right','None');

Align Components Horizontally While Distributing Them Vertically.   The following statement moves the push buttons horizontally to the center of their bounding box and adjusts their vertical placement. The 'Fixed' option makes the distance between the boxes uniform. Specify the distance in points (1 point = 1/72 inch). In this example, the distance is seven points. The push buttons appear in the center of the original bounding box. The bottom push button remains at the bottom of the original bounding box.

align([b1 b2 b3],'Center','Fixed',7);

Align Components Vertically While Distributing Them Horizontally.  The following statement moves the push buttons to the bottom of their bounding box. It also adjusts their horizontal placement to create a fixed distance of five points between the boxes. The push buttons appear at the bottom of the original bounding box.

align([b1 b2 b3],'Fixed',5,'Bottom');

Use Align Tools

If your figure has a standard menu bar, you can perform align and distribute operations on selected components directly in plot edit mode. Several options from the Tools menu save you from typing align function commands. The align and distribute menu items are highlighted in the following illustration.

The following steps illustrate how to use the Align Distribute tool to arrange components in a GUI. The tool provides the same options as the align function. discussed in Use the align Function.

  1. Select the Align Distribute Tool option from the Tools menu.

  2. In the Vertical panel chose the third Distribute option (the same as the align function Middle VerticalAlignment option). In the Horizontal panel, choose the first Align option (the same as the align function Left HorizontalAlignment option)

  3. Click Apply.

    The buttons align as shown.

You can also select the Align or Distribute option from the figure Tools menu to perform either operation immediately. For example, here are the six options available from the Align menu item.

For more information, see Align/Distribute Menu Options.

Set Colors Interactively

Specifying colors for Color, ForegroundColor, BackgroundColor, FontColor, and plotting object color properties can be difficult without seeing examples of colors. The uisetcolor function opens a GUI that returns color values you can plug into components when you create them or later, by using set. For example, the statement:

set(object_handle,'BackgroundColor',uisetcolor)

opens a color selector GUI for you to choose a color. When you click OK, it returns an RGB color vector that set assigns immediately. You get an error if the object does not have a property with the specified name or if the specified property does not accept RGB color values.

You can combine setting position and color into one line of code or one function, for example:

btn1 = uicontrol('String', 'Button 1',...
                  'Position',getrect,...
                  'BackgroundColor',uisetcolor)

When you execute the statement, first getrect executes to let you set a position using rbbox. When you release the mouse button, the uisetcolor GUI opens for you to specify a background color.

Set Font Characteristics Interactively

The uisetfont GUI gives you access to the characteristics of all fonts on your system. Use it to set font characteristics for any component that displays text. It returns a structure containing data that describes the property values you chose.

FontData = uisetfont(object_handle)

   FontData =
       FontName: 'Arial'
     FontWeight: 'bold'
      FontAngle: 'normal'
       FontSize: 10
      FontUnits: 'points' 

uisetfont returns all font characteristics at once. You cannot omit any of them unless you delete a field from the structure. You can use uisetfont when creating a component that has a String property. You can also specify the string itself at the same time by calling inputdlg, which is a predefined GUI for entering text strings. Here is an example that creates static text, sets the font properties, and positions it interactively:

 txt1 = uicontrol(...
            'Style','text',...
            'String',inputdlg('String','Static Text'),...
             uisetfont,'Position',getrect)

The inputdlg dialog box appears first, as shown here.

After you enter a string and click OK, the uisetfont dialog box opens for you to set font characteristics for displaying the string.

When you specify a font, style, and size and click OK, the getrect function executes (see Sketch a Position Vector). Drag out a rectangle for the text component and release the mouse button. The result looks something like this figure.

Generate Code to Set Component Properties

The techniques described in the preceding sections set properties of components interactively. However, you still need to create code in your GUI code file to enter the property values. The usual way to obtain the property values is by typing a get command, such as:

get(object_handle,'String')
ans =
      'Generate Data'

Then copy the string get returned and paste it into a set statement you have partially typed in your GUI code file:

set(object_handle,'String', 'Generate Data')

You can automate this process by running a helper function that generates set commands for components, properties, and values that you specify as arguments. You can find the function, called setprop, in the folder in the Help system that contains doc examples. See View and Run the setprop Function. Property values need not be character strings. The setprop function correctly translates the following MATLAB data types to text within set commands it generates:

Because it encodes strings, cell arrays, and function handles, setprop can output callbacks, such as a ButtonDownFcn, Callback, CloseRequestFcn, and so on. The function returns a "set string" for a component. You normally specify the component handle and the name of one of its properties. If you also provide a value for the property, setprop first sets and then returns the new value inside the set string. Here is the help text for the function:

function setstr = setprop(objhandle, property, value)

Generates a SET statement for a property of an object.
Copy the statement and paste it into your GUI code. 

setstr = setprop places the current figure in plot edit mode
for you to select a uicontrol or other object. It then opens
a GUI listing all properties of the selcted object. When you 
select a property, a SET command is returned for the current
value of that property. When called with no arguments, SETPROP 
returns a SET command that contains a generic name for the 
object, such as "pushbutton", which you should replace with
the actual variable name of its handle.

setstr = setprop(objhandle) opens a GUI listing all properties
of objhandle, the handle of an HG object. When you choose one,
a SET command is returned for the current value of the property
you selected.

setstr = setprop(objhandle,property) returns a SET command
for the current value of the property, or '' for an invalid
property name.

setstr = setprop(objhandle,property,value) returns a SET 
command for the specified value of the property, or '' for 
an invalid property name or value. If property is empty,
the listbox GUI opens to let you choose a property name.

The value can be a string, scalar, vector, cell array, HG 
handle or function handle. Properties consisting of structs
or objects are disregarded and return '' (empty).

If you call setprop with no input arguments, it prompts you to select a component or other graphic object. Click to select the object you want to set and press Enter. You then select a property of the object from a dialog box and a set string with its value is returned. When you select an object interactively in this way, setprop has no knowledge of its variable name. Therefore, it returns a generic variable name, which is:

You should replace the generic name with the variable name of its handle after pasting the set string into your code file.

Here is the output of setprop for a String property:

setprop(object_handle,'String')
ans = 
set(object_handle,'String','Generate Data')

You can assign a string in the call to setprop. To create multiline strings, use a cell array. For example:

setstr = setprop(object_handle,'string',{'eggs','milk','flour','sugar'})
setstr =
set(object_handle,'String',{'eggs','milk','flour','sugar'})

You can abbreviate property names as long as you make them unique. For example, obtain a Position property set string:

setprop(object_handle,'pos')
ans = 
set(object_handle,'Position',[20 20 60 20])

If you omit the property name, the function displays a GUI listing all the properties of the object.

setprop(object_handle)

When you select a property name from the list and click OK, setprop returns a set string for that property and its current value:

ans =
set(btn1,'FontName','MS Sans Serif')

The setprop function places its return value on the system clipboard. You can paste the result directly into your GUI code file. If you copy something else before pasting, copy the value printed for ans (or the variable you assigned values to) from the Command Window and paste it into your code.

Some property values (for example, matrices or cell arrays) can generate long statements. You can break long commands into continuation lines (...) to improve their readability, but it is not necessary to do so.

Combine the setprop and setpos functions to set the position of a component interactively and generate a set command for the new position. Try the following code, substituting an actual component handle for object_handle:

setstr = setprop(object_handle,'pos',setpos(object_handle))
=== Drag out a Position for object_handle 

After you drag out a rectangle in the figure, you receive a result that looks like this statement (but specifies your rectangle), which you can directly paste into your GUI code file:

setstr = set(hs2,'Position',[38 62 146 239]) 

View and Run the setprop Function

If you are reading this document in the MATLAB Help browser, you can access the setprop.m doc example file by clicking the following links. If you are reading on the Web or from a PDF, go to the corresponding section in the MATLAB Help Browser to use the links.

If you intend to modify the code of this example function, first save a copy of its code file in your current folder. (You need write access to your current folder to save files there.) Click the following links to copy the example files to your current folder and open them.

  1. Click here to copy the setprop file to your current folder

  2. Type edit setprop or click here to open the file in the MATLAB Editor

If you only want to run the function and inspect its code, follow these steps:

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

  2. Type edit setprop or click here to open the file in the MATLAB Editor (read only)

Summary of GUI Development Tools

The tips and tools described in the preceding sections can help you set up a GUI in less time and with less chance for typographical and other error. The techniques discussed are:

Familiarizing yourself with these tools can enhance your GUI development workflow and produce better results with less effort.

For more information on using interactive tools, see the following documentation:

  


Recommended Products

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