2016-11-11 11 views
1

これは私の宿題です。JFrameを拡張中にJPanelが正しく表示されない

私の指示: クラスGuessGame:このクラスには、JFrameオブジェクトを作成し、JFrameのサイズ、可視性および終了を設定するmain関数が含まれています。

クラスGuessGameFrame:GuessGameFrameクラスがJFrameを拡張します。したがって、GuessGameFrameクラスには、JFrameクラスで定義されたすべての変数とメソッドがあります。

私は重要な何かを省いた場合、私が知っていると私はより多くの詳細を追加することができますしてください、私は私の問題が何であるかを100%確実ではないが、私はJPanelのは、任意の助けをいただければ幸い正しく

が動作していないと信じて。

メインクラス:

public class GuessGame { 

      public static void main(String[] args){ 
        GuessGameFrame localGuessGameFrame = new GuessGameFrame(); 
        localGuessGameFrame.setVisible(true); //set visible 
        localGuessGameFrame.setSize(380,175); // set size 380 width 175 height 
        localGuessGameFrame.setDefaultCloseOperation(localGuessGameFrame.EXIT_ON_CLOSE); // needed to enable the red X button to close the program 
      } 
} 

拡張クラス:実行出力ウィンドウの

import javax.swing.*; 
import java.awt.*; 

public class GuessGameFrame extends JFrame 
    { 

    private int lastDistance; // distance between last guess and number 
    private Color background; // background color of application 

    private JFrame f; 
    static JPanel p; 
    private JButton b1; 
    private JLabel l1; 
    private JLabel l2; 
    JTextField t1 = new JTextField(8); 
    private JLabel l3; 

    //declare constructor 
    public GuessGameFrame() 
    { 
    //create our JFrame 
    f = new JFrame("Guessing game"); 

    //create our panel 
     p = new JPanel(); 
     p.setBackground(Color.MAGENTA); // background color is magenta 

     //create our labels 
     l1 = new JLabel("I have a number between 1 and 1000."); 
     l2 = new JLabel("Can you guess my number? Enter your first Guess:."); 
     l3 = new JLabel("Guess result appears here."); 
     //create our button 
     b1 = new JButton("New Game"); 

     //add button and label to panel 
     p.add(l1); // Adds label 1 
     p.add(l2); // adds label 2 
     p.add(t1); // adds textfield 1 
     p.add(l3); // adds label 3 
     p.add(b1); // adds button 1 

     //add panel to JFrame 
     f.add(p); 
    } 
} 

スクリーンショット:

enter image description here

私はそれがこのように見えることを期待enter image description here

答えて

4

GuessGameFrameがすでにJFrameあるので、あなたはGuessGameFrameクラスでJFrame fを削除する必要があります。

そして、あなたのコードを更新します。this.getContentPane().add(p);

+0

からthis.setTitle("Guessing game");

f.add(p);

f = new JFrame("Guessing game");は、これが働いていました!なぜそれがうまくいったのか、なぜか「これ」に焦点を当てて説明してください。 – GeekyDewd

+1

あなたのコードでは、GuessGameFrameはJFrame自体であり、別のJFrameを含んでいます。あなたはJFrame f(GuessGameFrameではなく)のUIを初期化し、localGuessGameFrame.setVisible(true)を呼び出すメインクラスでは動作しません。 – Jerry06

+1

@ Jerry06: 'this'と' getContentPane() 'は冗長ですが、 'GuessGameFrame'のインスタンスのメソッドを呼び出していることを確認してください。 – trashgod

関連する問題