matlaboopinheritancematlab-guide

How to declare inheritance of uicontrol objects in MATLAB


I'm learning how to programmatically create an app in MATLAB with a graphical user interface. I'm using MATLAB 2015a.

I don't understand why I am getting this error:

Error using GuiTitle
The specified superclass 'uicontrol' contains a parse error, cannot be found on MATLAB's search path, or
is shadowed by another file with the same name.

I'm trying to make a class called GuiTitle that has uicontrol as the superclass. My class GuiTitle looks like this:

classdef GuiTitle < uicontrol
    methods
        function obj = GuiTitle(text)
            if nargin == 0
                text = '';
            end

            obj@uicontrol('Style', 'text', 'String', upper(text));
        end
    end   
end

Here is my code:

function hello_gui
% Test GUI

GuiConstants % contains constants that 
GuiTitle %%

f = figure('Visible','off','Position',[POS_FROM_LEFT,POS_FROM_BOTTOM,...
                                       WINDOW_WIDTH,WINDOW_HEIGHT]);
set(f, 'MenuBar', 'none')

titleText    = 'process variable names';

%title = uicontrol('Style', 'text', 'String', upper(titleText));

title        = GuiTitle(titleText) %%

title.Position = [0, 0, WINDOW_WIDTH, WINDOW_HEIGHT];
title.FontSize = FONT_SIZE;

f.Visible = 'on';

end

When I comment out lines with %% and uncomment

title = uicontrol('Style', 'text', 'String', upper(titleText));

The window displays properly:

correct output

What am I missing?


Solution

  • uicontrol is a function that creates an object of type matlab.ui.control.UIControl:

    h = uicontrol;
    class(h)    % returns 'matlab.ui.control.UIControl'
    

    However, this class is sealed and cannot be used as a superclass:

    classdef myclass < matlab.ui.control.UIControl
       ...
    
    >> a=myclass
    Error using myclass
    Class 'matlab.ui.control.UIControl' is Sealed and may not be used as a superclass.
    

    Note that GUIs in MATLAB are designed very differently from what you might be used in other languages. There is no need to derive from UI classes to change their behavior, you define their behavior by setting callback functions:

    h = uicontrol;
    h.String = 'button';
    h.Callback = @(src,event) msgbox('pressed the button!');