简体   繁体   中英

getting index of an element in an array of JButtons. Java

I am coding a ticTacToe game. For that I created JButton and stored them into the array. When the user clicks that particular button, I want to know which button was clicked. I am trying to find which JButton was clicked in 'buttons' array to set the text of that particular button.

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

Assign the button number from the loop to their click event class.

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

also

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
    }
}

Edit: you probably should make the Button Number integer private/protected and add a get method.

it should work if you put this in the actionListener not quite sure if everything is written right

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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