简体   繁体   English

Swing-使用getComponent()更新所有JButton

[英]Swing - using getComponent() to update all JButtons

I am making a tictactoe game where each board piece is represented by a JButton. 我正在做一个单板游戏,其中每个棋子都由一个JButton表示。 When someone clicks the button the text is changed to "X" or "O". 当有人单击按钮时,文本将更改为“ X”或“ O”。 I am writing a reset function which resets the text in all the buttons to "". 我正在编写一个重置功能,该功能将所有按钮中的文本重置为“”。 I am accessing all the buttons from an array using getComponents() method. 我正在使用getComponents()方法访问数组中的所有按钮。

I just wondered what I am doing wrong because this bit compiles correctly 我只是想知道我在做什么错,因为此位可以正确编译

component[i].setEnabled(true);

but this bit does not 但这一点不

component[i].setText("");

I get a "cannot find symbol" error. 我收到“找不到符号”错误。 Please have a look at the code below. 请看下面的代码。 I only included the code I thought was necessary. 我只包含了我认为必要的代码。

    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();
}

getComponents () returns an array of Component s, which does not have a setText(String) method. getComponents ()返回一个Component数组,该数组没有setText(String)方法。 You should either keep your JButton instances as class members (this is the way I strongly suggest), and use them directly, or loop through all the Component objects, check if it is a JButton instance. 您应该将JButton实例保留为类成员(这是我强烈建议的方式),然后直接使用它们,或者遍历所有Component对象,检查它是否为JButton实例。 If it is, explicitly cast it as a JButton , then call setText(String) on it. 如果是,则将其显式转换为JButton ,然后对其调用setText(String) Eg 例如

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("");
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM