Java: 如何删除匿名 ActionListeners?

Java: How to remove anonymous ActionListeners?

我正在为学校制作测验。问题有几个按钮,按下时会显示新问题并为 4 个答案的按钮创建 4 个不同的 ActionListeners。 现在我需要在按下一个按钮后删除 4 ActionListeners 。 我可以从按钮本身删除 ActionListener,但我也想删除其他 3 个 ActionListeners

每个新 ActionListener 看起来像这样:

btAnswer1.addActionListener(new java.awt.event.ActionListener()
    {
        @Override
        public void actionPerformed(java.awt.event.ActionEvent evt)
        {
            lResult.setForeground(Color.red);
            lResult.setText("Wrong Answer :(");
            // The team is changed.
            if (aktTeam == 1)
            {
                aktTeam = 2;
                lAktTeam.setText("Team 2");
            }
            else
            {
                 aktTeam = 1;
                lAktTeam.setText("Team 1");
            }
            // Here, this ActionListener is removed. But the others should
            // be removed too.
            btAntwort1.removeActionListener(this);
        }
    });

我希望有人能提供帮助。 :)

编辑:由 davidxxx 解决。谢谢!

1) 在您的示例中,您没有从添加侦听器的同一个 btn 中删除 ActionListener

你把它加到btAnswer1:

btAnswer1.addActionListener(new java.awt.event.ActionListener()...

但是你把它从 btAntwort1 中删除了:

btAntwort1.removeActionListener(this);

所以,它应该不起作用。

Now I need to remove the 4 ActionListeners after one button was pressed.

2) 如果在我们的用例中删除与按钮关联的所有 ActionListener 是有效的,您可以执行:

for( ActionListener listener : btAntwort1.getActionListeners() ) {
        btAntwort1.removeActionListener(listener);
 }

否则,如果您不想删除与该按钮关联的所有 ActionListener,则不应内联匿名 ActionListener 实例,以便在需要时保留对它们的引用从按钮中删除它们。
例如这样做:

    ActionListener actionListenerOne = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
             ...
        }
    };

    ActionListener actionListenerTwo = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
             ...
        }
    };

例如,现在您可以添加到按钮的 ActionListener 个实例上有两个引用。

所以你可以这样做:

JButton button = ...;
button.addActionListener(actionListenerOne);
button.addActionListener(actionListenerTwo);

以后:

button.removeActionListener(actionListenerOne);
button.removeActionListener(actionListenerTwo);