繁体   English   中英

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

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

我正在做一个单板游戏,其中每个棋子都由一个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();
}

getComponents ()返回一个Component数组,该数组没有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("");
        }

    }
}

暂无
暂无

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

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