2012-01-04 52 views
2

我有一種情況,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; 
    } 
    } 
} 

回答

2

不要實例化,每次處理監聽對象。使用getActionListeners()方法來驗證是否添加了監聽器。

public class MyClass { 
    private ActionListener fListener = new MyListener(); 
    private JButton fComponent = new JButton("Test"); 

    public MyClass() { 
     fComponent.addActionListener(fListener); 
    } 
    public void setListener() { 
    if (fComponent.getActionListeners().length == 0) { 
     fComponent.addActionListener(fListener); 
    } 
    } 

    public void removeListener() { 
    if (fComponent.getActionListeners().length !=0) { 
     fComponent.removeActionListener(fListener); 
    } 
    } 
} 

方法ActionListener[] getActionListeners()返回所有ActionListeners的陣列加入到這一JButton

+0

我認爲,這是一個很好的解決方案。 – Lion 2012-01-04 03:06:04

+0

@AVD。代碼中的邏輯要求不會有其他監聽器被添加到組件,而不是由add/removeListener方法控制的那個監聽器,在我的應用程序中沒有保證。我將修改我的示例以使這種情況更加明確。 – Kavka 2012-01-04 03:17:08

+0

@Kavka - 感謝您寶貴的建議。 – adatapost 2012-01-04 03:20:25

2

是否有必要不斷添加和刪除組件中的監聽器?你可以只是禁用組件,或者有一個標誌可以用來確定是否可以運行該操作?

您可以將偵聽器包裝在您定義的另一個偵聽器中嗎?包絡監聽器可以有一個布爾開關,您可以翻轉來控制委派給真正的監聽者。

如果程度較重,你絕對要刪除和添加監聽器,你可以做如下,與AVD的解決方案一擰:

public void setListener() { 
    // java.util.List and java.util.Arrays 
    List<ActionListeners> listenerList = Arrays.asList(fComponent.getActionListeners()); 

    if (!listenerList.contains(fListener) { 
     fComponent.addActionListener(fListener); 
    } 
} 

public void removeListener() { 
    List<ActionListeners> listenerList = Arrays.asList(fComponent.getActionListeners()); 

    if (listenerList.contains(fListener) { 
     fComponent.removeActionListener(fListener); 
    } 
} 
+0

擁有一個標誌來控制MyListener類的'actionPerformed'方法中的動作看起來是一種可行的選擇。 – Kavka 2012-01-04 03:26:31