-2

How can i add ActionListeners to the MemoryFeld objects in the nested for-loop ?

for(int i = 0; i < 4; i++){
    for(int k = 0; k < 4; k++)
        grid.add(new MemoryFeld(teile[k][i]));
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Snick
  • 1

1 Answers1

0

You have to add it just like any other ActionListener

for(int i = 0; i < 4; i++){
    for(int k = 0; k < 4; k++) {
        MemoryFeld thing = new MemoryFeld(teile[k][i]);
        thing.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Will print out message and object to prove it's
                // different from the other ones
                System.out.println("This thing was pressed " + x);
            }
        }); 
        grid.add(thing);
    }
}

Otherwise you could create a function for MemoryFeld like so

public MemoryFeld addListener(ActionListener newListener) {
    this.addActionListener(newListener);
    return this;
}

This will allow you to do this

for(int i = 0; i < 4; i++){
    for(int k = 0; k < 4; k++) {
        grid.add(new MemoryFeld(teile[k][i]).addListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Will print out message and object to prove it's
                // different from the other ones
                System.out.println("This thing was pressed " + x);
            }
        }));
    }
}

However, personally I think this is harder to read and doesn't really help anything.

JDrost1818
  • 1,116
  • 1
  • 6
  • 23
  • Thank you very much. I figured it out myself but your answer is exactly where my fault was. I just had to make a reference variable in the for-loop for memoryFeld (as you did) and it worked perfectly fine. Nonetheless thank you very much for the answer ! – Snick Jul 09 '15 at 11:34