gpt4 book ai didi

Java:构造函数不工作

转载 作者:行者123 更新时间:2023-11-30 05:54:26 24 4
gpt4 key购买 nike

我在使用 GUI 构造函数时遇到问题。它应该是井字游戏的 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
}
}
}
}

最佳答案

尽管名为 ButtonConstructor,但您拥有的函数不是构造函数。

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

如果没有看到更完整的代码 View ,我不能肯定地说(您肯定省略了大部分代码),但很可能您根本没有调用您提供给我们的函数,而是使用隐含的无参数构造函数。尝试将函数重命名为我在上面给出的签名。

关于Java:构造函数不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9356320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com