Reputation:
I have a JMenuItem callback that calls a new instance of a derived class of JFrame.
Whenever the JMenuItem callback is called, the original popup is not brought back to the front of my main application. Instead, it creates a new instance and a new window popup (so there are two or more of the same derived class).
How do I make it so there is at most one derived class instance at all time?
Upvotes: 4
Views: 6886
Reputation: 13632
If there really should never be more than one instance of your derived class, you can make it a Singleton, e.g.
public class MyFrame extends JFrame {
private static MyFrame instance = null;
private MyFrame() {
// Private to prevent instantiation.
}
public static MyFrame getInstance() {
if(instance == null) {
instance = new MyFrame();
}
return instance;
}
}
You simply call MyFrame.getInstance()
when you need to get an instance rather than using new, and will get the same one every time (it will be created the first time). e.g.
JFrame myFrame = MyFrame.getInstance();
// now call methods upon myFrame to make it pop up, etc.
If you'll be doing this from more than one place, then it would probably make sense to create a further static method inMyFrame
and place the code in there. e.g.
public static void popUp() {
JFrame myFrame = getInstance();
// now call methods upon myFrame to make it pop up, etc.
}
Then you can simply call MyFrame.popUp()
.
Upvotes: 3