我有一種情況,JComponent需要根據類的其他字段的狀態添加或刪除監聽器。聽衆不應該被添加多次,當然,它只能被刪除一次。使用類字段存儲偵聽器並使用值來控制向組件註冊/註銷偵聽器的操作是否是一種很好的做法。使用null賦值來控制監聽器的添加和刪除
我心目中的代碼是這樣的(修改,使其明確指出的JComponent提供給類別代碼):
public class MyClass {
private ActionListener fListener = null;
private JComponent fComponent;
public MyClass(JComponent component) {
fComponent = component; // for example, component = new JButton("Test");
}
public void setListener() {
if (fListener == null) {
fListener = new MyListener();
fComponent.addActionListener(fListener);
}
}
public void removeListener() {
if (fListener != null) {
fComponent.removeActionListener(fListener);
fListener = null;
}
}
}
我認爲,這是一個很好的解決方案。 – Lion 2012-01-04 03:06:04
@AVD。代碼中的邏輯要求不會有其他監聽器被添加到組件,而不是由add/removeListener方法控制的那個監聽器,在我的應用程序中沒有保證。我將修改我的示例以使這種情況更加明確。 – Kavka 2012-01-04 03:17:08
@Kavka - 感謝您寶貴的建議。 – adatapost 2012-01-04 03:20:25