JTree:如何获取一片叶子的文字?

时间:2014-09-26 05:52:55

标签: java swing jtree

我希望以格式获取JTree的文本:

  1. Root
  2. 节点1
  3. leaf1
  4. leaf2< -------点击
  5. 节点2
  6. 当我点击叶子时,我在JPanel中留下了信息

1 个答案:

答案 0 :(得分:2)

这是一个简单的例子:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;


public class TestFrame extends JFrame {

    private JLabel lbl;
    private JTree tree;

    public TestFrame() {
        init();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void init() {
        tree = new JTree();
        tree.getSelectionModel().addTreeSelectionListener(getListener());

        lbl = new JLabel("empty");

        add(new JScrollPane(tree));
        add(lbl,BorderLayout.EAST);
    }

    private TreeSelectionListener getListener() {
        return new TreeSelectionListener() {

            @Override
            public void valueChanged(TreeSelectionEvent e) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)  tree.getLastSelectedPathComponent();
                lbl.setText(node == null ? "empty" : node.toString());
            }
        };
    }

    public static void main(String args[]) {
        new TestFrame();
    }

}

tutorial中阅读更多内容。