MATLAB Creating Graphical User Interfaces

(Barry) #1
Lay Out a UI Programmatically

% Make figure visible after adding components
hs.fig.Visible = 'on';


function hs = addcomponents
% add components, save handles in a struct
hs.fig = figure('Visible','off',...
'Resize','off',...
'Tag','fig');
hs.btn = uicontrol(hs.fig,'Position',[10 340 70 30],...
'String','Plot Sine',...
'Tag','button',...
'Callback',@plotsine);
hs.ax = axes('Parent',hs.fig,...
'Position',[0.20 0.13 0.71 0.75],...
'Tag','ax');
end


function plotsine(hObject,callbackdata)
theta = 0:pi/64:6*pi;
y = sin(theta);
plot(hs.ax,theta,y);
end
end
This code performs the following tasks:



  • The main function, myui, calls the addcomponents function. The addcomponents
    function returns a structure, hs, containing the handles to all the UI components.

  • The addcomponents function creates a figure, an axes, and a button, each with
    specific Position values.

    • Notice that the Resize property of the figure is 'off'. This value disables the
      resizing capability of the figure.

    • Notice that the Visible property of the figure is 'off' inside the addcomponents
      function. The value changes to 'on' after addcomponents returns to the calling
      function. Doing this delays the figure display until after MATLAB adds all the
      components. Thus, the resulting UI has a clean appearance when it starts up.



  • The plotsine function plots the sine function inside the axes when the user clicks
    the button.

Free download pdf