开发者

Java Swing; JFrame Popup

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开发者_如何学C class).

How do I make it so there is at most one derived class instance at all time?


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().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜