MATLAB: How to put a waitbar in an existing figure in MATLAB 7.8 (R2009a)

guihandle graphicsMATLABwaitbar

I would like to put a waitbar in an existing figure, such as a GUI figure, instead of having it appear in a separate window.

Best Answer

To put a waitbar in an existing figure, you must transfer all the elements of a waitbar out of the default separate figure window and put it them on the existing figure.
Specifically, you must assign the parent of all these elements to be a handle to your existing figure rather than the handle to the separate figure. See the following code as an example of how to do this:
%grabs a handle 'f' to a figure.
f = figure;
% Creates a WAITBAR in a new figure (by default)
h = waitbar(0,'Please wait...'); %
% The child of the waitbar is an axes object. Grab the axes
% object 'c' and set its parent to be your figure f so that it now
% resides on figure f rather than on the old default figure.
c = get(h,'Children');
set(c,'Parent',f); % Set the position of the WAITBAR on your figure
set(c,'Units','Normalized','Position',[.5 .5 .3 .05]);
% Close the default figure
close(h);
% The above steps only need to occur once to place the waitbar on the figure.
% Now when you go to use the WAITBAR you can just call the waitbar with two
% inputs: waitbar(x,h) where x is how much of the bar you want filled and f
% is the handle to your figure.
steps = 1000;
for step = 1:steps
% computations take place here
waitbar(step / steps,f)
pause(.01)
end