user1809923
user1809923

Reputation: 1255

Matlab opens new figure in Callback despite hold

I am creating a GUI with MATLAB's GUIDE. Say, the GUI consists of an axis called axis1 and a slider called slider1. Further say I wanted to plot something (e.g. a box) into axis1 and change the box's height with the slider.

I tried doing this by adding a listener to the slider like so:

hListener = addlistener(handles.slider1,'Value','PostSet',@(src,evnt)boxHeightChange(src,evnt, handles.figure1));

in the GUI's opening function. I further defined:

function boxHeightChange(src, event, figname)
   handles = guidata(figname);
   % delete "old" box
   delete(handles.plottedHandle);
   % bring axis in focus
    axes(handles.axes1);
   % plot the new box (with changed size)
    hold on; boxHandle = plotTheBox(event.AffectedObject.Value); hold off
    handles.plottedHandle = boxHandle;
    % update saved values
    guidata(figname, handles);
end

This works, but always opens a new figure to plot the resizable box into instead of drawing into handles.axes1. I do not understand why, since I call axes(handles.axes1); and hold on; Any idea that might explain the behavior?

Upvotes: 3

Views: 706

Answers (2)

Pet Detective
Pet Detective

Reputation: 86

Most plotting functions let you pass a name value pair 'Parent', ah where ah specifies the axes to plot on. I think this is the best way to handle your problem. Your actual plotting command seems to be wrapped in the plotTheBox function, so you will have to pass the axes handle in somehow.

Your plot command will look something like this:

plot(a,'Parent',handles.axes1)

You solved the problem a different way on your own, but I think you should do it my way because it's more explicit and it's less likely to lead to unforeseen problems.

Upvotes: 0

user1809923
user1809923

Reputation: 1255

I will post a solution to my own question.

Apparently the Callback of a listener is not declared as a "GUI Callback" which is why the GUI can not be accessed from within boxHeightChange if the GUI option "command-line accessibility" is not set to "On".

That means: In GUIDE go to Tools -> GUI options and set "Command-line accessibility" to "On".

Upvotes: 2

Related Questions