簡體   English   中英

如何在Swing中獲得JFrame

[英]How to get a JFrame in Swing

我正在開發一個簡單的應用程序,我需要訪問從並非總是可以直接訪問它的不同位置初始化程序時創建的JFrame (例如,contentPane為空,因此SwingUtilities.getWindowAncestor(Component)將不起作用)。 還有其他方法嗎? 例如,這是一個可用於初始化的類:

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);
         });
     }
}

我需要在其他地方使用它,例如

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

因此,為了共享主框架,我傾向於將其包裝在單例類中,然后提供一個靜態方法。 也許還有另一種方法?

您可以將其存儲在靜態引用中:

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);
         });
     }
}

如下調用:

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

這是一個丑陋的解決方案,也許您可​​以查看“設計模式”以獲得更好的解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM