Question

I've seen some posts on this before, but I haven't been able to find one regarding actionListeners. I am trying to create tic-tac-toe using an array of JButtons. How do I add an action listener to them whilst using a for loop temporary variable if at all possible? Thanks for your help in advance.

JButton jb [] = new JButton[9];
int checkB [] = new int[9];
public SomethingSimple(){
    JPanel p1 = new JPanel();
   p1.setLayout(new GridLayout(3, 3, 5, 5));
   p1.setBackground(Color.red);
  for (int i = 0; i < jb.length; i++){
    checkB[i] = 0;
  }
  for (int i = 0; i < jb.length; i++){
      jb[i] = new JButton("");
      p1.add(jb[i]);
      jb[i].addActionListener(new ActionListener(){
           @Override
          public void actionPerformed(ActionEvent e){
              jb[i].setText("O");
          }
      });
  }
  add(p1);
 }

Thanks everyone for your help, you gave me some solutions!

Was it helpful?

Solution

Create a final int inside the forloop; You cant access a local variable from your class to a anonymous class..

solution:

     for (int i = 0; i < jb.length; i++){
          jb[i] = new JButton("");
          final int index = i;
          jb[i].addActionListener(new ActionListener(){
               @Override
              public void actionPerformed(ActionEvent e){
                  jb[index].setText("O");
              }
          });
          p1.add(jb[i]);

      }

OTHER TIPS

I think the best solution will be to move ActionListener to a separate class:

public class MyActionListener implements ActionListener {
    private final JButton button;

    public MyActionListener(JButton button) {
        this.button = button;
    }

    @Override
    public void actionPerformed(ActionEvent e){
        button.setText("O");
    }        
}

And change your code like this:

for (int i = 0; i < jb.length; i++) {
    jb[i] = new JButton("");
    p1.add(jb[i]);
    jb[i].addActionListener(new MyActionLisener(jb[i]));
}    

Local and anonymous classes can only access final local variables, so do something like

final JButton btn = jb[i];

inside the for loop immediately after you create the new JButton and then you can refer to btn inside actionPerformed.

This is coming from a C# programmer, who is 15, so take it with a grain of salt. First as I understand your question, you want to add the actionListener to all of your Jbuttons in the array jb, with a for loop. Basically in my java experience, you'll have to implement actionListener into your class(or into whatever class that'll act as the actual listener). Then your code should look something like this:

for(int i = 0; i < jb.length(); i++)
{
  jb[i].addActionListener(class that implements the listener);
}

Please tell me if I misunderstood your question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top