I have a Frame class that I put one Jtree on it, now I developed a TreeSelectionListener for my tree. since my tree is in my Frame class how I can access to my tree ?
I want to know witch node pressed by user. I create a stataic class from my frame class but I think this way is wrong please advice me.
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 ...
}
Just create a constructor for JTreeSelectionListener
that takes your 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) {
}
}
Another approach is to combine the listener functionality with your frame class:
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 ...
}
}
精彩评论