Adjust Programmatic UI Layouts Interactively

Laying out a programmatic UI 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 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 Distribute 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.

    Note:   The following sections describe some techniques for interactively refining the appearance of UIs. If you are building a UI that opens a saved FIG-file, re-saving that file will preserve most of the properties you interactively change. If your program file creates a new figure whenever you open it, then you must specify all changed properties in the program file itself to keep the UI up-to-date.

Set Positions of Components Interactively

If you do not like the initial positions or other properties of UI components, you can make manual adjustments to them. By placing the figure in plot edit mode, you can use your mouse to move, resize, align, and change various components properties. Then, you can read out the values of properties you changed and copy them into your UI 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. Get the component's Position value from the Property Inspector. Execute this command to open the Property Inspector.

    Or, use dot notation to get the value at the command prompt.
    ans =
       15.2500  333.0000  106.0000   20.0000

  6. Assign the Position property to that value (ans).

    object_handle.Position = [15.2500 333.0000 106.0000 20.0000];

    Tip   Instead of using a separate set command, after you decide upon a position for the object, you can modify the statement in your code file that creates the object to include the Position parameter and value.

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)])
disp('=== Select, move and resize object. Use mouse and arrow keys.')
disp('=== When you are finished, press Return to continue.')
rect = handle.Position;
To experiment with the function, enter the following code in the Command Window:
hfig = figure; 
hsl = uicontrol('Style','slider') 
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:

You also can use the functional form to pass in the handle of the object you want to inspect, for example:
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.

Scroll in the help window to view descriptions of other properties.

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:

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:

  • If your program file opens a saved FIG-file each time it runs, save (or re-save) the figure itself.

  • If your program file creates the figure each time it runs, save the property value in your program file.

You can obtain the new property value using dot notation and the property name. For example, this command gets the BackgroundColor property value of object_handle and stores it in the variable, bc.

bc = object_handle.BackgroundColor;

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,

  • A figure window must have focus.

  • The mouse cursor must be within the figure window.

  • Your left mouse button must down.

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 UI 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 = object_handle.Units;
    object_handle.Units = get(gcf,'Units');
    object_handle.Position = rect;
    object_handle.Units = myunits;
    rect = [];
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 UI code file, and then execute it:

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

  2. Put the following statement in your UI 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 UI 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 UI 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',...

  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',...

  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',...
Two MATLAB utilities for composing UIs 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

Here are two ways to align groups of components:

  • Use the align Function — This approach allows you to align components programmatically using points as the unit of measurement. The align function does not change the Units property of the components.

  • Use Align Distribute Tool — This approach allows you to align components interactively using pixels as the unit of measurement. The Align and Distribute tool does not change the Units property of the components.

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


The following table lists the possible values for these parameters.

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,'Position',[30 10 60 30],'String','B1');
b2 = uicontrol(fh,'Position',[50 50 60 30],'String','B2');
b3 = uicontrol(fh,'Position',[10 80 60 30],'String','B3');

    Note:   Each of the three following align examples starts with these unaligned push buttons and repositions them in different ways. In practice, when you create buttons with uicontrol and do not specify a Position, their location is always [20 20 60 20] (in pixels). That is, if you keep creating them with default positions, they lie on top of one another.

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 Distribute Tool

If your figure has a standard menu bar, you can perform align and distribute operations on selected components directly in plot edit mode. 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 UI. The tool provides the same options as the align function. discussed in Use the align Function.

  1. Select Tools > Edit Plot.

  2. Select the components that you want to align.

  3. Select Tools > Align Distribute Tool.

  4. In the Vertical panel, choose 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)

  5. 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.

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 dialog that returns color values you can use to set these properties. For example, this command opens a dialog that allows the user to choose a color:

object_handle.BackgroundColor = uisetcolor;
When the user clicks OK, the uisetcolor function returns an RGB values.

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

btn1 = uicontrol('String', 'Button 1',...
When you execute the statement, first getrect executes to let you set a position using rbbox. When you release the mouse button, the uisetcolor dialog opens for you to specify a background color.

Set Font Characteristics Interactively

The uisetfont dialog 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 dialog that allows you to enter text strings. Here is an example that creates static text and sets the font properties.
f = figure('Position',[300 300 385 285]);
txt1 = uicontrol(f,...
            'String',inputdlg('String','Static Text'),...
             uisetfont,'Position',[50 200 150 40]);
The inputdlg dialog box appears first.

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 text appears in the figure window.

Was this topic helpful?