2

我正在制作一个井字游戏,其中每个棋盘都由一个 JButton 表示。当有人单击按钮时,文本将更改为“X”或“O”。我正在编写一个重置函数,它将所有按钮中的文本重置为“”。我正在使用 getComponents() 方法访问数组中的所有按钮。

我只是想知道我做错了什么,因为这个位编译正确

component[i].setEnabled(true);

但这一点不

component[i].setText("");

我收到“找不到符号”错误。请看下面的代码。我只包含了我认为必要的代码。

    JPanel board = new JPanel(new GridLayout(3, 3));

    JButton button1 = new JButton("");
    JButton button2 = new JButton("");
    JButton button3 = new JButton("");
    JButton button4 = new JButton("");
    JButton button5 = new JButton("");
    JButton button6 = new JButton("");
    JButton button7 = new JButton("");
    JButton button8 = new JButton("");
    JButton button9 = new JButton("");

    board.add(button1);
    board.add(button2);
    board.add(button3);
    board.add(button4);
    board.add(button5);
    board.add(button6);
    board.add(button7);
    board.add(button8);
    board.add(button9);

public void reset()
{
    Component[] component = board.getComponents();

    // Reset user interface
    for(int i=0; i<component.length; i++)
    {
        component[i].setEnabled(true);
        component[i].setText("");
    }

        // Create new board logic
        tictactoe = new Board();
        // Update status of game
        this.updateGame();
}
4

1 回答 1

7

getComponents ()Component返回一个没有方法的 s 数组setText(String)。您应该将您的JButton实例保留为类成员(这是我强烈建议的方式),并直接使用它们,或者遍历所有Component对象,检查它是否是一个JButton实例。如果是,则将其显式转换为JButton,然后调用setText(String)它。例如

public void reset()
{
    Component[] component = board.getComponents();

    // Reset user interface
    for(int i=0; i<component.length; i++)
    {
        if (component[i] instanceof JButton)
        {
            JButton button = (JButton)component[i];
            button.setEnabled(true);
            button.setText("");
        }

    }
}
于 2013-09-09T19:34:15.423 回答