我创建了一个jframe。此jframe包含一个jlabel,其中包含一些jbuttons。JButtons有一个ActionListener(称为MainFramelistener)。单击arrowButton
按钮时,代码执行了方法。此方法用foodButton.removeActionListener(new MainFrameListener());
但是,尽管我删除了侦听器,但按钮仍然有两个按钮。当然,我已经在Internet上搜索以解决该问题,我找到了一系列代码,其中显示了一个按钮的听众数量。
System.out.println("Count of listeners: " + ((JButton) e.getSource()).getActionListeners().length);
我第一次单击按钮时说有两个按钮。当我单击arrowButton
时,将打开另一个菜单,并删除按钮。一切都像我想要的。当我单击arrowBackButton
时,应用程序将我发送回大型机。那很完美。但是,当我再次单击arrowButton
时,控制台说我有两个侦听器为按钮注册。点击播放两次的声音。
我不明白这一点,因为我删除了听众。有没有更好的方法来删除听众?
foodButton.removeActionListener(new MainFrameListener());
不会删除任何内容,因为您正在删除从未添加到foodButton
的新创建的对象。保留对听众的参考,然后以后将其删除:
MainFrameListener listener = new MainFrameListener();
foodButton.addActionListener(listener);
//and later somewhere else
foodButton.removeActionListener(listener);
,但我的建议是避免首先添加/删除听众。