Normally, you want to have just one single instance of a GUI window running. This is the so-called “singleton” concept.
There are several reasons why you normally want to make sure that only one instance of a particular GUI window can exist at a given time:
The solution to these problems is to make sure that only one instance of a GUI window will be open at a given time.
The good news is: It is quite easy to make use of the singleton concept within Matlab™. Here is how:
function mySingletonGUI % MYSINGLETONGUI A GUI window stub demonstrating the singleton concept % in Matlab(tm). % (c) 2012, Till Biskup % 2012-05-31 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Construct the components %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Make GUI effectively a singleton singleton = findobj('Tag',mfilename); if (singleton) figure(singleton); return; end % Construct the components hMainFigure = figure('Tag',mfilename,... 'Name','My singleton GUI',... 'Units','Pixels',... 'Position',[300,300,350,250],... 'Resize','off',... 'NumberTitle','off', ... 'Menu','none','Toolbar','none'... );
Although it appears to be quite a bit of code, the crucial part is only a very few lines. But besides that, what you see in the listing above is an example of a generic GUI function.
Please note: Although the above example will just create and open a pretty boring (empty) figure window, it is a working and tested example.
The basic idea is to give your main GUI window (the one that you create with the figure
command) a unique name, called “Tag”.
At the beginning of your GUI function, you just search for an object with that tag (via findobj
). If the search returns a value, just bring that figure to focus (simply calling figure()
with the respective figure handle as argument) and return.
That's it.