2014-01-30 50 views
0

我使用customButtons作爲Jbutton將的負載容器此構造函數的Java。我獲得通過按鈕名稱(但可通過配置文件):泄漏與NetBeans

getComponent("btn1"); 

我已經做到了這種方式有按鈕的漂亮的列表,功能的簡單概述,以正確的面板參考「 jpt「來獲得編譯器給我的所有幫助。

按鈕的順序,數量和選擇也需要非編程人員配置 - 我發現按鍵變量名稱的列表,以正常工作)。

的問題是:Netbeans的7.4給我的警告「在構造該泄漏」(9號線),這是真的,因爲我做的。有沒有更正確的方法來達到相同的結果?

public class CustomButtons extends javax.swing.JPanel { 

    CustomJPanel jpt; 
    HashMap<String, Component> components; 

    public CustomButtons (CustomJPanel jpt) { 
    this.jpt = jpt; 
    initComponents(); 
    components = getAllComponentsInContainer(this); 
} 

public Component getComponent(String name) { 
    return components.get(name); 
} 

private HashMap<String, Component> getAllComponentsInContainer(Container root) { 
    HashMap<String, Component> comps = new HashMap<>(); 
    for (Component c : root.getComponents()) { 
     comps.put(c.getName(), c); 
     if (c instanceof Container) { 
      comps.putAll(getAllComponentsInContainer((Container) c)); 
     } 
    } 

    return comps; 
} 
+0

你的類名應該以大寫字母開頭 - 它使識別類和變量更容易。 – Njol

+0

謝謝,這是一個匿名化神器,修復。 – user3218163

回答

0

只要getComponents()是保證你所撥打getAllComponentsInContainer(this)時被初始化,您可能不會太在意的警告 - 它主要有警告你關於你的實例沒有被完全沒有初始化的可能性。

如果你想避免的警告,你可以改變getAllComponentsInContainer只接受getComponents()的結果,而不是:

components = getAllComponents(getComponents()); 
... 
private HashMap<String, Component> getAllComponents(Component[] containerComponents) { 
    HashMap<String, Component> comps = new HashMap<>(); 
    for (Component c : containerComponents) { 
     comps.put(c.getName(), c); 
     if (c instanceof Container) { 
      comps.putAll(getAllComponents((Container) c).getComponents()); 
     } 
    } 

    return comps; 
} 

或者,也可以,例如,添加一個initialise方法類需要構造完成後調用(但是這意味着你可能會忘記的地方叫):

public void initialise() { 
    components = getAllComponents(getComponents()); 
} 
0

你可以把實現方法getAllComponentsInContainer在構造函數中只,並設置所有的實例變量,因爲它是在同一個類,你是作者,我不能寫確切的實現,因爲不知道你在做什麼在initComponents()方法。

+0

initComponents()是swing/awt框架做的事情。建議編輯刪除搖擺標籤,我做了。 (我無法審查/接受編輯,因爲我在此期間編輯過這篇文章)。 – user3218163

+0

@ user3218163我不知道擺的,但你問這個問題是一個普遍的設計問題。讓我把我的答案在其他的方式,我建議不要在構造函數中,而不是在構造此方法的這寫代碼調用getAllComponentsInContainer()。這是可行的解決方案,因爲您正在編寫此類代碼。告訴我,如果它不明確。 – Vipin