JTree没有出现在SplitPane的左侧ScrollPane中

时间:2018-06-19 07:50:32

标签: java swing jscrollpane jtree splitpane

我正在尝试使用两侧的scrollpane实现splitpane。左侧应该显示我试图实现的JTree,但它不起作用,我无法看到树。

我不确定我做错了什么。我的代码类似于:

public class SplitPane extends JFrame {
    DefaultTreeModel treeModel;
    JEditorPane editorPane = new JEditorPane();
    DefaultMutableTreeNode Root;
    JTree tree;
    JScrollPane leftscrollPane;
    JScrollPane rightscrollPane;

    public SplitPane() {
        setSize(600,400);
        tree = new JTree(Root);
        Root = new DefaultMutableTreeNode("");
        setTree();                   // I connect all the nodes here
        treeModel = new DefaultTreeModel(Root);
        tree = new JTree(Root);
        tree.setRootVisible(false);

        leftscrollPane = new JScrollPane(tree);
        rightscrollPane = new JScrollPane(editorPane);

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        splitPane.setLeftComponent(leftscrollPane);
        splitPane.setRightComponent(rightscrollPane);

        splitPane.setDividerLocation(160);

        setVisible(true);

        splitPane.setPreferredSize(new Dimension(600,400));
        getContentPane().add(splitPane);
    }
}

然后进行初始化,我只做SplitPane newpane = new SplitPane();

我认为我已经正确添加了所有节点,因为当我这样做时

Enumeration e = Root.preorderEnumeration();
while(e.hasMoreElements()) {
    System.out.println(e.nextElement());
}

我按顺序看到所有节点。

我做错了什么?我真的很感激一些帮助和反馈!

1 个答案:

答案 0 :(得分:0)

你的第二个

tree = new JTree(Root);
必须使用模型初始化

tree = new JTree(treeModel);

您可以删除树的第一次初始化,因为它会被第二次初始化覆盖。

这是一个正在运行的例子:

public class SplitPane extends JFrame {

  private MutableTreeNode createTree() {
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
    root.add(new DefaultMutableTreeNode("child 1"));
    root.add(new DefaultMutableTreeNode("child 2"));

    return root;
  }

  public SplitPane() {

    setSize(600, 400);

    // create model and add nodes
    TreeModel model = new DefaultTreeModel(createTree());

    // initialize tree, set the model
    JTree tree = new JTree(model);
    tree.setRootVisible(false);

    JScrollPane leftScrollPane = new JScrollPane(tree);
    JScrollPane rightScrollPane = new JScrollPane(new JLabel("Text ..."));

    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    splitPane.setLeftComponent(leftScrollPane);
    splitPane.setRightComponent(rightScrollPane);
    splitPane.setDividerLocation(200);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.getContentPane().add(splitPane);
    this.setVisible(true);
  }
}

你可以通过简单地将它安装在这样的地方来运行这个例子:

        SplitPane splitPane = new SplitPane();