2017-12-23 25 views
-1

私は基本的なプログラムを作成してスイングGUIを使用して学習しています。何らかの理由で私がプログラムを実行するとフレームに表示されません。フレームに設定されているにもかかわらずSwing GUIにJavaメニューバーが表示されない

public class GUITest { 

private static int windowWidth = 500; 
private static int windowHeight = 500; 

private static JFrame frame; 
private static JMenuBar menuBar; 

public static void main(String[] args){ 
    build(); 
} 

private static void build(){ 
    windowGen(); 
    menuGen(); 
} 

private static void windowGen(){ 
    JFrame frame = new JFrame(); 
    frame.setLayout(null); 
    frame.setSize(windowWidth,windowHeight); 
    frame.setVisible(true); 
} 

private static void menuGen(){ 
    JMenuBar menuBar = new JMenuBar(); 
    JMenu menuFile = new JMenu("File"); 
    JMenuItem menuFileExit = new JMenuItem("Exit"); 
    menuFile.add(menuFileExit); 

    menuBar.add(menuFile); 

    frame.setJMenuBar(menuBar); 
} 
} 

なぜこのようなことがありますか?

+0

のレイアウトを定義することではありません –

+0

'setVisible(true)'は最後に呼び出す必要があります。なぜなら、すべてのコンポーネントがレイアウトされているからです。メニューバーを変更する必要がある場合は、少し異なります。 – markspace

+0

ahhhhありがとうございました=] –

答えて

0

は、上記宣言の静的変数を参照しますが、新しいものを作成していない、それは最初のエラーであり、別のは、あなたがフレームを表示する前にそれを追加するには、JFrameの

public class GUITest { 

private static int windowWidth = 500; 
private static int windowHeight = 500; 

private static JFrame frame; 
private static JMenuBar menuBar; 

public static void main(String[] args){ 
    build(); 
} 

private static void build(){ 
    windowGen(); 
    menuGen(); 
} 

private static void windowGen(){ 
    frame = new JFrame(); 
    frame.setLayout(null); 
    frame.setSize(windowWidth,windowHeight); 
    frame.setVisible(true); 
} 

private static void menuGen(){ 
    JMenuBar menuBar = new JMenuBar(); 
    JMenu menuFile = new JMenu("File"); 
    JMenuItem menuFileExit = new JMenuItem("Exit"); 
    menuFile.add(menuFileExit); 

    menuBar.add(menuFile); 

    frame.setJMenuBar(menuBar); 
} 
} 
+0

トップで静的変数を削除しますか? または上記のようにJFrameという単語を削除するだけですか? 私はレイアウトを少し経験したので意図的にレイアウトを割り当てていません。 –

+0

この例では、前にJFrameクラスを削除するだけで十分でしょう。新しい変数 –

+0

私はちょうど結果なしでこれらの両方を試しました: 1)あなたが示したように(メニューバーと同じ) 2)最初にそれらを初期化 ?私の興味をそそるのは、私のウィンドウはまだメニューではないようです。 –

関連する問題