Graphical User Interfaces (GUIs) can enhance the usability of your MATLAB programs and provide an interactive environment for users. In this article, we will walk you through the basics of creating GUIs in MATLAB using the uifigure function, and we will focus on adding buttons and textboxes. We will provide multiple examples to help you get started.
1. Creating a Simple uifigure:
A uifigure is the main window of your GUI application. You can add different UI components, such as buttons and textboxes, to this figure.
A basic app window can be created like this:
% Create a uifigure fig = uifigure('Name', 'My First GUI Application');
2. Adding a Button:
Let's add a button to this window.
% Create a button button = uibutton(fig, 'push', 'Text', 'Click Me', 'Position', [150, 100, 100, 22]); % Define a callback function for the button button.ButtonPushedFcn = @(btn, event) disp('Button Clicked!');
When the button is clicked, the text "Button Clicked!" is displayed in the Matlab command window.
- To create the button using uibutton, we need to pass the GUI figure variable to it, so that Matlab knows on which window to place the button.
- Text is the name of an argument and its value is passed after that, in this case a string which says, "Click Me".
- Next is the relative Position of button within the figure. Four numbers are used to specify this.
- First value specifies how far to the right from the left border should be the button.
- 2nd value specifies how far to the top from the bottom border should be the button.
- 3rd value specifies the length and 4th value specifies the width of the button.
- The keyword ButtonPushedFcn is associated with an uibutton and is used to specify what happens when the button is pushed.
3. Adding a textbox:
Let's add a textbox now.
% Create a uifigure fig = uifigure('Name', 'My GUI Application'); % Create a button button = uibutton(fig, 'push', 'Text', 'Trim Text', 'Position', [150, 100, 100, 22]); % Create a textbox textbox = uitextarea(fig, 'Position', [50, 50, 200, 40]); % Define a callback function for the button button.ButtonPushedFcn = @(btn, event) trim_text(textbox); % Custom function to trim the text to retain only first 5 characters function trim_text(textbox) current_text = cell2mat(textbox.Value); updated_text = current_text(1:5); textbox.Value = updated_text;end
- When the button is clicked, whatever text we had previously entered into it, will be trimmed after the first 5 characters.
- The handle to the textbox is passed to the the trim_text function which means the function has access to all the associated properties of the textbox, such as 'Value'.
This is how you create a simple GUI with buttons and textboxes. This is just the beginning. Very interesting GUI's could be created with Matlab. But thats for another time.
Comments
Post a Comment