调用JTree并输入scrollpane

时间:2014-09-28 14:21:35

标签: java swing components jtree

我使用this教程创建了一个JTree。 现在我想调用这个类并将它放在ScrollPane中。

但是当我使用这个

    TreeMainMenu tree = new TreeMainMenu();
    JScrollPane MainMenu = new JScrollPane(tree);

它只获得默认树。我需要了解如何从其他类调用Components来使用它们。

JTree的:

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

public class TreeMainMenu extends JTree {


private DefaultMutableTreeNode top = new DefaultMutableTreeNode("TOP");


public TreeMainMenu() {

    APNode();
    JTree tree = new JTree(top);



 tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
}


private void APNode() {
    DefaultMutableTreeNode category = null;
    DefaultMutableTreeNode node1 = null;
    DefaultMutableTreeNode node2 = null;
    DefaultMutableTreeNode node3 = null;

    category = new DefaultMutableTreeNode("top");
    top.add(category);

    node1 = new DefaultMutableTreeNode(new Node("top-1"));
    category.add(node1);
    node2 = new DefaultMutableTreeNode(new Node("node1"));
    node1.add(node2);
    node2 = new DefaultMutableTreeNode(new Node("node2"));
    node1.add(node2);
    node2 = new DefaultMutableTreeNode(new Node("node3"));
    node1.add(node2);
    node2 = new DefaultMutableTreeNode(new Node("node4"));
    node1.add(node2);

}

private class Node {
    public String nodeName;

    public Node(String node) {
        nodeName = node;
    }

    public String toString() {
        return nodeName;
    }

}
}

1 个答案:

答案 0 :(得分:0)

您的TreeMainMenu课程已经JTree,因此您无需创建新课程JTree tree = new JTree(top);

您使用节点创建新树,但TreeMainMenu的实例具有默认节点。因此,您可以使用TreeMainMenu extends JPanel并将您的树(在构造函数中创建)添加到该面板,或者您需要将TreeMainMenu的实例用作JTree,您的构造函数可以如下:< / p>

public TreeMainMenu() {

    APNode();
    setModel(new DefaultTreeModel(top));
    getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
}