2015-02-10 172 views
2

我正在創建一個TicTacToe遊戲。我已經把所有的後端與按鈕的ActionListeners,添加的按鈕面板,設置了框起來等添加JPanel到JFrame時遇到困難

然而,當我運行程序我的JPanel似乎沒有被添加到JFrame 。我嘗試過使用不同的佈局,仔細檢查我是否已經將.add行放入了所有內容,而且之前的所有帖子似乎都導致了我相信我已經涉及的內容。

如果這是非常簡單的事情,我很抱歉。

import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener;  
import javax.swing.*;  

public class BasicGUI { 
    private String piece="O"; 
    protected static Boolean player=true; 
    private static final JFrame frame = new JFrame("BasicGUI"); 
    private static final JPanel panel=new JPanel(new GridLayout(4,3)); 
    protected static final JButton[] cells= new JButton[9]; 
    private static final JButton exitButton=new JButton("Exit"); 
    private static final JButton restartButton=new JButton("Restart"); 

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

    //Set up frame 
    private static void createWindow(){ 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(450, 600); 
     //Tried adding panel here and below 
     //frame.add(panel, BorderLayout.CENTER); 
     frame.setVisible(true); 
     //Tried using getContentPane too 
     //frame.getContentPane().add(panel, BorderLayout.CENTER); 
    } 

    //Add action listeners to buttons 
    private static void createButtons(){ 
     for(int i=0; i<9; i++){ 
      cells[i]=new JButton(); 
      cells[i].addActionListener(new ButtonHandler()); 
      panel.add(cells[i]); 
     } 
     exitButton.addActionListener(new ExitHandler()); 
     restartButton.addActionListener(new RestartHandler()); 
     panel.add(exitButton); 
     panel.add(restartButton); 
     frame.add(panel); 
    } 

    public String getPiece(){ 
     return piece; 
    } 
    protected void setPiece(String s){ 
     this.piece=s; 
    } 
} 

謝謝你的幫助。

回答

2

添加面板調用這兩個方法後:

frame.pack(); 
frame.setVisible(true); 
+0

我的啞巴-.- 各種非常感謝你 – 2015-02-10 14:02:41

+0

如果它是有幫助的,請關閉後... – aurelius 2015-02-10 14:04:15

+0

它發生大家,不用擔心! – aurelius 2015-02-10 14:10:41