sanmiyom
sanmiyom

Reputation: 43

How to add and delete items on MATLAB Gui

I'm a new MATLAB GUI user. I'm trying to add various number of items, let's say static texts on the GUI. The number and the position of items will be calculated according to input.

A = uicontrol('Style','pushbutton','Position',[0,0,50,50])

This code adds a pushbutton but I don't know how to use this button after creating that in this way. Does this A have its own handles or hObject? How can I make MATLAB display('someone pressed the button') when I clicked on the button?

Thanks in advance.

Upvotes: 0

Views: 133

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

A is a uicontrol object. Its property 'callback' defines what action is executed when the button is pressed. Specifically, the property can contain (see here for more detailed information and additional possibilities):

  1. A char vector, which will be executed as code.
  2. Sometimes the char vector this is just a call to a function that does the actual work.
  3. A handle to a function, which will get called with two input arguments, specifying the object and the event.

So, in your case, you can do either of the following:

  1. (Note that the quote whithin the char vector symbols are escaped by duplicating):

    set(A, 'callback', 'disp(''Someone pressed the button'')')
    
  2. (Note that I am defining the as anonymous, and that it does not take any inputs):

    dispFun = @()disp('Someone pressed the button')
    set(A, 'callback', 'dispFun')
    

    With this approach, the function needs to be in scope when the button is pressed, so that it can be found by the interpreter.

  3. (Note the function must take two inputs):

    dispFun = @(o,e)disp('Someone pressed the button')
    set(A, 'callback', dispFun)
    

    With this approach there are no scope restrictions. The function handle defines the anonymous function itself, which gets assigned to the callback.

    On the other hand, if the function resides in a file, say dispFun_file.m, using

    set(A, 'callback', @dispFun_file)
    

    again assigns a handle to the function, but that function is now on a different place. So if the function is modified (or removed from memory with clear functions) the callback will change.

Upvotes: 1

Related Questions