Java:构造函数不工作

Sam*_*nch 2 java constructor

我正在处理我正在使用的GUI构造函数的问题.它应该是一个tic tac toe游戏的GUI,但我的按钮都没有被创建,我的GUI窗口是空白的.我真的很困惑.我创建了一个TicTacToePanel实例并将其添加到主JFrame中.

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
        }
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Bor*_*lid 6

尽管被调用ButtonConstructor,你拥有的函数不是构造函数.

在Java中,构造函数必须共享其父类的名称(并且没有返回类型).正确的签名将是public TicTacToePanel().

我不能肯定地说没有看到更完整的代码视图(你肯定省略了大部分内容),但很可能你没有调用你提供给我们的函数,而是使用隐含的no-参数构造函数.尝试将函数重命名为我上面给出的签名.