MATLAB Creating Graphical User Interfaces

(ff) #1

Add UI Components to App Designer Programmatically


Most UI components are available in the App Designer Component Library for you to
drag and drop onto the canvas. Occasionally, you might need to add components
programmatically in Code View. Here are a few common situations:


  • Creating components that are not available in the Component Library. For example,
    an app that displays a dialog box must call the appropriate function to display the
    dialog box.

  • Creating components dynamically according to run-time conditions.


When you add UI components programmatically, you must call the appropriate function to
create the component, assign a callback to the component, and then write the callback as
a helper function.

Create the Component and Assign the Callback


Call the function that creates the component from within an existing callback (for a list of
component functions, see “Designing Apps in App Designer”). The StartupFcn callback
is a good place to create components because that callback runs when the app starts up.
In other cases, you might create components within a different callback function. For
example, if you want to display a dialog box when the user presses a button, call the
dialog box function from within the button's callback function.

When you call a function to create a component, specify the figure or one of its child
containers as the parent object. For example, this command creates a button and
specifies the figure as the parent object. In this case, the figure has the default name that
App Designer assigns (app.UIFigure).

b = uibutton(app.UIFigure);

Next, specify the component's callback property as a function handle of the form
@app.callbackname. For example, this command sets the ButtonPushedFcn property
of button b to a callback function named mybuttonpress.

b.ButtonPushedFcn = @app.mybuttonpress;

15 Component Choices and Customizations

Free download pdf