如何将ActionListener添加到匿名对象?

时间:2015-07-08 14:12:21

标签: java swing object actionlistener anonymous

如何将ActionListeners添加到嵌套for循环中的MemoryFeld对象?

for(int i = 0; i < 4; i++){
    for(int k = 0; k < 4; k++)
        grid.add(new MemoryFeld(teile[k][i]));
    }
}

1 个答案:

答案 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);
            }
        }));
    }
}

但是,我个人认为这很难阅读,对任何事情都没有帮助。