如何将ActionListeners添加到嵌套for循环中的MemoryFeld对象?
for(int i = 0; i < 4; i++){
for(int k = 0; k < 4; k++)
grid.add(new MemoryFeld(teile[k][i]));
}
}
答案 0 :(得分:0)
您必须像任何其他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);
}
}
否则你可以为MemoryFeld创建一个函数,如此
public MemoryFeld addListener(ActionListener newListener) {
this.addActionListener(newListener);
return 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);
}
}));
}
}
但是,我个人认为这很难阅读,对任何事情都没有帮助。