2012-02-20 88 views
1

我遇到了一個我正在研究的GUI構造函數的問題。它應該是一個tic tac toe遊戲的GUI,但是我的按鈕都沒有被創建,而且我的GUI窗口是空白的。我很困惑。我創建了TicTacToePanel的一個實例並將其添加到主JFrame中。Java:構造函數不工作

class TicTacToePanel extends JPanel implements ActionListener { 

public void actionPerformed(ActionEvent e) { 
} 
//Creates the button array using the TicTacToeCell constructor 
private TicTacToeCell[] buttons = new TicTacToeCell[9]; 
//(6) this constructor sets a 3 by 3 GridLayout manager in the panel 
///then creates the 9 buttons in the buttons arrray and adds them to the panel 

//As each button is created 
///The constructer is passed a row and column position 
///The button is placed in both the buttons array and in the panels GridLayout 
///THen an actionListener this for the button 
public void ButtonConstructor() { 
    //creates the layout to pass to the panel 
    GridLayout mainLayout = new GridLayout(3, 3); 
    //Sets a 3 by 3 GridLayout manager in the panel 
    this.setLayout(mainLayout); 
    int q = 1; //provides a counter when creating the buttons 
    for (int row = 0; row < 3; row++) //adds to the current row 
    { 
     for (int col = 0; col < 3; col++) //navigates to the correct columns 
     { 
      System.out.println("Button " + q + " created"); 
      buttons[q] = new TicTacToeCell(row, col); 
      mainLayout.addLayoutComponent("Button " + q, this); 
      this.add(buttons[q]); //adds the buttons to the ticTacToePanel 
      buttons[q].addActionListener(this); //this sets the panel's action listener to the button 
      q++; //increments the counter 
     } 
    } 
} 
} 
+1

找不到任何調用按鈕創建例程的TicTacToePanel構造函數! – Favonius 2012-02-20 04:50:57

+0

「TicTacToeCell」在哪裏定義,它有什麼作用?更多的代碼會有所幫助。 – casablanca 2012-02-20 04:51:55

+1

僅僅因爲你命名的東西「ButtonConstructor」不會使它成爲構造函數。所以不要稱之爲構造函數(這會混淆事物);它只是你必須明確調用的任何舊方法。您沒有包含足夠的相關信息或代碼,也沒有描述您的問題的性質足以期望得到很多幫助。 – 2012-02-20 04:52:18

回答

5

儘管名爲ButtonConstructor,但您所擁有的功能不是構造函數。

在Java中,構造函數必須共享其父類的名稱(並且沒有返回類型)。正確的簽名將是public TicTacToePanel()

我不能確定沒有看到你的代碼更完整的視圖(你肯定省略了大部分視圖),但很可能你沒有調用你提供給我們的函數,而是使用隱含的無參構造函數。嘗試將函數重命名爲上面給出的簽名。

+0

謝謝你,似乎解決了這個問題! – 2012-02-20 05:58:08