获取 JButton 数组中元素的索引.爪哇岛



我正在编写一个ticTacToe游戏。为此,我创建了 JButton 并将它们存储到数组中。当用户单击该特定按钮时,我想知道单击了哪个按钮。我正在尝试查找在"按钮"数组中单击了哪个 JButton 以设置该特定按钮的文本。

public class tester extends JFrame{
    boolean crossed = false;
    JButton[] buttons = new JButton[9];
    public tester(){
        super("The title");
        this.setLayout(new GridLayout(3,2));
        for(int x = 0 ; x < buttons.length; x++){
            buttons[x] = new JButton();
            this.add(buttons[x]);
            buttons[x].addActionListener(new tickSquare());
        }

        this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
        this.setSize(400, 400);
        this.setVisible(true);
    }
    public class tickSquare implements ActionListener{
        public void actionPerformed(ActionEvent e){
        }
    }

    public static void main(String[] args){
        new tester();
    }
}   

将循环中的按钮编号分配给其点击事件类。

for(int x = 0 ; x < buttons.length; x++)
{
        buttons[x] = new JButton();
        this.add(buttons[x]);
        buttons[x].addActionListener(new tickSquare(x));
}

public class tickSquare implements ActionListener
{
    public int ButtonNumber;
    public tickSquare(int x)
    {
        ButtonNumber = x;
    }
    public void actionPerformed(ActionEvent e)
    {
        //do something with the button number
    }
}

编辑:您可能应该将按钮编号整数设为私有/受保护并添加一个 get 方法。

如果你把它放在actionListener中,它应该可以工作不太确定是否一切都写对了

for(int i=0;i<buttons.length;i++){
if(e.getSource()==buttons[i]){
buttons[i].setText("x");
}
}

最新更新