【问题标题】:Swing - using getComponent() to update all JButtonsSwing - 使用 getComponent() 更新所有 JButton
【发布时间】:2013-09-13 08:03:38
【问题描述】:

我正在制作一个井字游戏,其中每个棋盘都由一个 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();
}

【问题讨论】:

    标签: java swing jbutton


    【解决方案1】:

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

    【讨论】:

    • 哦,我的印象是,当我执行 component[i].setText() 时,我将 component[i] 视为普通的 JButton。谢谢,我会试试你说的。仅供参考,我在原始代码中确实将 JButton 作为私有类成员 - 你是说我应该在每 9 个按钮上单独设置文本?
    • @jimbo123 在这种情况下不是。此时,在您的代码中,您知道您有 Component 实例,但您并不确切知道您正在处理 Component 的哪个子类。您应该知道getComponents() 将返回添加到您的board 对象的所有 组件,而不仅仅是您的游戏按钮。
    • 是的,我在某处读过这个,我认为在我的情况下没问题,因为我只在面板中添加了按钮。我明白为什么必须把它扔掉。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    相关资源
    最近更新 更多