2013-04-23 71 views
2

我想在Java上使用Swing組件(Boggle類型的遊戲)做一個小遊戲。 現在我已經設置了它的方式,它基本上可以立即打開遊戲 - 但我希望有一個啓動窗口有兩個按鈕 - 「教程」和「播放」。我已經有了功能(我的教程按鈕只是打開一個包含所有東西的新窗口)我只是不確定如何創建第二個JFrame,然後在按Play時切換到它(或者更確切地說,創建一個JFrame,然後切換到JButton按下時已經創建的那個)。我想我可能會導致新的JFrame在同一位置打開,而舊的JFrame會變得不可見 - 但我希望能有一個更簡單的解決方案。更改佈局/框架響應按鈕按

我也想在遊戲完成時做到這一點,自動切換到一個小統計頁面 - 所以任何信息將不勝感激。

這是我迄今爲止的情況下,如果你們想看我的代碼(我還沒有掛上回車鍵發送userWord進行驗證和評分在我的其他類,或填充在tileGrid中圖塊對象,或定時器....但將其隨後所有的來了!)

public class Game implements Runnable { 
public void run(){ 

    final JFrame frame = new JFrame("Boggle"); 
    frame.setLocation(500,200); 

    // Input - holds typing box 

    final JLetterField typingArea = new JLetterField(1); 
    typingArea.setFocusTraversalKeysEnabled(false); 
    typingArea.setEditable(true); 
    typingArea.setFocusable(true); 
    typingArea.requestFocusInWindow(); //also this request isn't being granted.. 
             //if anyone could explain why i would love you 
             // I want the focus on the TextField on startup 


    frame.add(typingArea, BorderLayout.SOUTH); 
    typingArea.addKeyListener(new KeyAdapter() { 
     public void keyPressed (KeyEvent e) { 
      if (e.getKeyCode() == KeyEvent.VK_ENTER) { // enter key is pressed 
       String userWord = typingArea.getText().toLowerCase(); 
       typingArea.setText(""); 

      } 
     } 
    }); 


    final JLabel status = new JLabel("Running..."); 

    // Main playing area 

    GridLayout tileGrid = new GridLayout(4,4); 
    final JPanel grid = new JPanel(tileGrid); 
    frame.add(grid, BorderLayout.CENTER); 

    // Reset button 
    final JPanel control_panel = new JPanel(); 
    frame.add(control_panel, BorderLayout.NORTH); 


    final ImageIcon img = new ImageIcon("Instructions.png", "My Instructions..."); 
    final JButton info = new JButton("Help"); 
    info.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      final JFrame infoFrame = new JFrame("Tutorial"); 
      infoFrame.setLocation(500,50); 
      JLabel tutorialImg = new JLabel(img); 
      int w = img.getIconWidth(); 
      int h = img.getIconHeight(); 
      infoFrame.setSize(w, h); 
      infoFrame.add(tutorialImg); 
      infoFrame.setVisible(true); 
     } 
    }); 
    control_panel.add(info); 

    // Put the frame on the screen 
    frame.pack(); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 

} 

public static void main(String[] args){ 
    SwingUtilities.invokeLater(new Game()); 
} 

} 

回答

5
+0

感謝@mKorbel即時通訊仍然是相當新的編程和我不能確定鏈接在「標題到OutOfMemory」是什麼是相關的。 卡布局似乎是我正在尋找雖然 – gadu 2013-04-23 08:39:50

+0

您的JButton總是創建一個新的JFrame,與JLabel和圖像作爲圖標,這些形式的對象留在JVM內存中,並增加一個新的JFrame – mKorbel 2013-04-23 08:52:03