简体   繁体   中英

How to get a JFrame in Swing

I'm working on a simple app and I need to access JFrame created when initializing a program from different places where it's not always possible to access it directly (eg contentPane is empty so SwingUtilities.getWindowAncestor(Component) won't work). Is there any other way to do this? For example, this is a class resposinble for initialization:

public final class Application{
     public static void start(){
         //Empty screen with menu
         SwingUtilities.invokeAndWait(() -> {
                JFrame frame = new JFrame("Main frame");
                JMenuBar menuBar = new JMenuBar();
                JMenu menu = new JMenu("Start");
                menuBar.add(menu);
                frame.setJMenuBar(menuBar);
         });
     }
}

And I need to use it from some other places, eg

JPanel panel = new JPanel();
//initialize the panel
//push it to the content pane of Main frame

So, in order to share the main frame I tend to wrap it in a singleton class and then provide a static method. Maybe there is another way of doing that?

You can store it in a static reference:

public final class Application{
     static JFrame mainFrame;                            //static attribute 
     public static void start(){
         //Empty screen with menu
         SwingUtilities.invokeAndWait(() -> {
                JFrame frame = new JFrame("Main frame");
                mainFrame = frame;                        //Storing in static attribute
                JMenuBar menuBar = new JMenuBar();
                JMenu menu = new JMenu("Start");
                menuBar.add(menu);
                frame.setJMenuBar(menuBar);
         });
     }
}

An call it as follows:

JPanel panel = new JPanel();
//initialize the panel
Application.mainFrame.getContentPane().add(panel);

This is a ugly solution maybe you can review Design Patterns for a better solution:

http://www.tutorialspoint.com/design_pattern/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM