views:

765

answers:

1

In MATLAB 2008a, is there a way to allow a class method to act as a uicontrol callback function without having to make the method public? Conceptually, the method should not be public because it should never be called by a user of the class. It should only be called as a result of a UI event triggering a callback. However, if I set the method's access to private or protected, the callback doesn't work. My class is derived from hgsetget and is defined using the 2008a classdef syntax.

The uicontrol code looks something like:


methods (Access = public)
   function this = MyClass(args)
      this.someClassProperty = uicontrol(property1, value1, ... , 'Callback', ...
      {@(src, event)myCallbackMethod(this, src, event)});
      % the rest of the class constructor code
   end
end

The callback code looks like:


methods (Access = private)  % This doesn't work because it's private
   % It works just fine if I make it public instead, but that's wrong conceptually.
   function myCallbackMethod(this, src, event)
      % do something
   end
end
+2  A: 

Storing the function handle of the callback as a private property seems to workaround the problem. Try this:

classdef MyClass
    properties
        handle;
    end

    properties (Access=private)
        callback;
    end

    methods
        function this = MyClass(args)
            this.callback = @myCallbackMethod;
            this.handle = uicontrol('Callback', ...
                {@(src, event)myCallbackMethod(this, src, event)});
        end
    end

    methods (Access = private)
        function myCallbackMethod(this, src, event)
            disp('Hello world!');
        end
    end
end
b3