0

我正在尝试实现一个两边都有滚动窗格的拆分窗格。左侧应该显示一个我正在尝试实现的 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());
}

我按顺序看到所有节点。

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

4

1 回答 1

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();
于 2018-06-19T08:31:32.593 回答