Java: конструктор не работает - PullRequest
2 голосов
/ 20 февраля 2012

У меня проблема с конструктором 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
        }
    }
}
}

1 Ответ

6 голосов
/ 20 февраля 2012

Ваша функция, несмотря на то, что она вызывается ButtonConstructor, не является конструктором.

В Java конструктор должен совместно использовать имя своего родительского класса (и не иметь возвращаемого типа). Правильная подпись будет public TicTacToePanel().

Я не могу сказать наверняка, не увидев более полное представление о вашем коде (вы наверняка пропустили большую его часть), но вполне вероятно, что вы вообще не вызываете функцию, с которой вы нам предоставили, а скорее используете подразумеваемый конструктор без аргументов. Попробуйте переименовать функцию в подпись, которую я дал выше.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...