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]));
}
}
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]));
}
}
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.