我正在处理我正在处理的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
}
}
}
}
答案 0 :(得分:5)
尽管被称为ButtonConstructor
,但您拥有的功能不是构造函数。
在Java中,构造函数必须共享其父类的名称(并且没有返回类型)。正确的签名是public TicTacToePanel()
。
我不能肯定地说没有看到更完整的代码视图(你肯定省略了大部分代码),但很可能你没有调用你提供给我们的功能,而是使用暗示无参数构造函数。尝试将函数重命名为我上面给出的签名。