2011-04-02 117 views
0

我有一個框架類,我把一個Jtree,現在我開發了TreeSelectionListener我的樹。因爲我的樹在我的Frame類中,我怎樣才能訪問我的樹?java中的繼承問題

我想知道用戶按下的女巫節點。 我從我的框架類創建一個stataic類,但我認爲這種方式是錯誤的,請指教我。

public Frame1(){ 
    JTree jtree = new Jtree(); 
    public static Frame1 THIS; 
    public Frame(){ 
    init(); 
    THIS = this; 
    } 
    public static getTHIS(){ 
     return THIS; 
    } 
} 

public class jtreeSelectionListener implements TreeSelectionListener{ 

//here I need to access my jtree object, what should I do in this case? 
// now I do like this . Frame1.getTHIS.jtree ... 
} 
+0

可能是通過獲取源在'valueChanged(TreeSelectionEvent e)'事件''e.getSource()'並在JTree中解析它 – 2011-04-02 09:20:03

+0

WhiteFAng的答案是現貨,雖然你應該小心,當產生t帽子靜態關鍵字。它的確有它的用處,但大多數時間都被誤用來通過創建一個全局變量來規避對設計的限制。 – Newtopian 2011-04-02 09:38:03

回答

5

只要創建一個構造JTreeSelectionListener這需要你JTree

public class Frame1 extends JFrame { 
    private JTree jtree = new JTree(); 

    public Frame1() { 
     jtree.addTreeSelectionListener(new JTreeSelectionListener(jtree)); 
    } 
} 

public class JTreeSelectionListener implements TreeSelectionListener { 
    private JTree jtree; 

    public JTreeSelectionListener(JTree jtree) { 
     this.jtree = jtree; 
    } 

    public void valueChanged(TreeSelectionEvent e) { 
    } 
} 
+0

感謝您的幫助和支持,我不知道爲什麼我忘了寫這樣的代碼: - ?這個網站的名字真的是正確的名字;) – Amir 2011-04-02 10:09:32

3

另一種方法是將監聽的功能與你的框架類組合:

public class Frame1 extends JFrame implements JTreeSelectionListener { 
    private JTree jtree = new JTree(); 

    public Frame1() { 
     jtree.addTreeSelectionListener(this); 
    } 

    public void valueChanged(TreeSelectionEvent e) { 
     // can now access jtree directly ... 
    } 
} 
+0

+1是的,如果類是簡單的我傾向於喜歡這種方法爲聽衆。 – WhiteFang34 2011-04-02 09:54:38

+0

謝謝你的回答是正確的,也謝謝 – Amir 2011-04-02 10:09:49