java中的继承问题

时间:2011-04-02 09:15:11

标签: java swing inheritance

我有一个Frame类,我在其上放了一个Jtree,现在我为我的树开发了一个TreeSelectionListener。既然我的树在我的Frame类中,我怎么可以访问我的树?

我想知道用户按下的女巫节点。 我从我的框架类创建一个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 ...
}

2 个答案:

答案 0 :(得分: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) {
    }
}

答案 1 :(得分: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 ...
    }
}