Felix
Felix

Reputation: 1

Adding an outside int into an action listener

I have to do a very small project for school: making a game of tic tac toe in Java using JButtons and I have a short question.

Here's the code:

public void FensterAufbauen() {
    int i = 0;  
    myPanel.setLayout(null);
    myButton.setText("");
    myButton.setBounds(40,70,80,80);
    myButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent arg0) {
            if (i % 2 == 0){
            myButton.setText("X");
            }
            else {
            myButton.setText("O");
            }
            i++;
        }
    });
}

Now how would I add the int i into the action listener (I have this for all 9 buttons so I can't just define i inside the listener)? I am sorry in advance if anything here seems sloppy - I'm pretty new to Java

Upvotes: 0

Views: 41

Answers (1)

user7655213
user7655213

Reputation:

i has to be final if you want to access it from within an anonymous inline class:

final int i = 0;

That, of course, will mean you can no longer change it. Thus, instead, declare i as a non-final, private variable in the surrounding class, rather than a local variable. Or you could also declare i as a private variable inside your ActionListener, just above the actionPerformed() function.

Upvotes: 1

Related Questions