matlabmatlab-figurematlab-app-designer

How to make a uifigure the current one in Matlab


I have a script that creates multiple uifigures:

% create fig1
fig1 = uifigure('Name', 'Figure 1');

% create fig2
fig2 = uifigure('Name', 'Figure 2');

% set fig2 as the current figure
set(0, 'currentfigure', fig2);

% get the current figure
gcf

I want the second uifigure to be the current one, so I set it with the third command. However, when I then use gcf to get the current figure, it is still the first one. Here is the output from the command line:

ans = 

  Figure (1) with properties:

      Number: 1
        Name: ''
       Color: [0.9400 0.9400 0.9400]
    Position: [514 371 560 420]
       Units: 'pixels'

  Show all properties

What is the problem?


Solution

  • This code does what you want, creates two figures and puts the second figure on top

    % create fig1
    fig1 = uifigure('Name', 'MyFig 1');
    
    % create fig2
    fig2 = uifigure('Name', 'MyFig 2');
    
    % set fig2 as the current figure
    drawnow
    figure(fig2)
    

    You will see that figure 2 is on top instead of figure 1, which was the case with your original code. If you call gcf, it will create a new figure which will also be called "figure 1" since none of the figures created by uifigure have the "HandleVisibility" property set to "on". In my code, I changed the figure names slightly so that if you run gcf, you will see that it is creating a new figure called Figure 1, not switching to the first figure created by this code.

    If you want gcf to work and see figure 2, you can turn HandleVisbility on when you create the figure. Replace the line above for creating figure 2 with this code:

    fig2 = uifigure('Name', 'MyFig 2', 'handlevisibility', 'on');