2016-05-08 8 views
0

私は単純なアプリケーションを開発中で、直接アクセスすることができない別の場所からプログラムを初期化するときに作成するJFrameにアクセスする必要があります(contentPaneが空のためSwingUtilities.getWindowAncestor(Component) ' t仕事)。これを行うための他の方法はありますか?スウィングでJFrameを取得する方法

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

そして、私は、例えば、いくつかの他の場所からそれを使用する必要があります。たとえば、これは、初期化のためのクラスですresposinble

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

したがって、メインフレームを共有するために、シングルトンクラスでラップし、静的メソッドを提供する傾向があります。多分それには別の方法がありますか?

答えて

2

あなたは、静的参照して、それを保存することができ、次のよう

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/

関連する問題