【问题标题】:how to get the text of an item in JTree and pass its value to another class如何在 JTree 中获取项目的文本并将其值传递给另一个类
【发布时间】:2015-07-26 08:11:57
【问题描述】:

嘿,我是 JAVA 的新手,我正在做一个项目,此时我被卡住了,我想做的是...我已经制作了一个 JTree,其中列出了一些项目,现在我想获取一个JTree 的选定项,将其存储在 String 对象中并将其传递给另一个类,在那里我可以对其进行进一步的操作... 这是我尝试过的

Demo d;    //creating object of the class where i want to pass the value 
String s;

tree.addTreeSelectionListener(new TreeSelectionListener()
 {
      public void valueChanged(TreeSelectionEvent e) 
      {
        node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();



   System.out.println("You selected " + node);
    s=node.toString();
    d.getVal(s);   //getVal() is the method in class Demo which will receive                                             
                      my String object 
  }
});

当我运行程序时,getVal() 中返回一个空值,而不是 JTree 项的文本,请帮助..

【问题讨论】:

    标签: java


    【解决方案1】:

    在代码中我看不到任何d=new Demo(...);(或类似的以获取Demo 的实例)。没有它,您只需声明变量 d,但您永远不会创建该类的实例。

    【讨论】:

    • 你要么必须事先创建一个 Demo 实例,比如说 Demo d=new Demo();并在运行时将选择交给它:d.setString(s);或者您在运行时创建对象,例如 Demo d1=new Demo(s);
    • 如果它始终是同一个演示对象(如控制器),您可以尝试像这样绑定元素:stackoverflow.com/questions/21787386/…
    • 变量 s 怎么样?它设置正确吗?接下来,你想用Demo 类实现什么?您能否在此处发布该代码以帮助我们了解发生了什么?
    【解决方案2】:

    我已经初始化了构造函数并在其中传递了 String 对象,而不是在函数中传递它。这就是我所做的

    Demo d;    //creating object of the class where i want to pass the value 
    String s;
    
    tree.addTreeSelectionListener(new TreeSelectionListener()
     {
          public void valueChanged(TreeSelectionEvent e) 
          {
            node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
    
    
    
       System.out.println("You selected " + node);
        s=node.toString();
        d=new Demo(s);                                   
    
      }
    });
    

    感谢大家的建议.... :-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-10
      • 2016-03-08
      • 1970-01-01
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      相关资源
      最近更新 更多