0

我使用这里提到的第一个示例来创建我的 JTree,但我想在 JscrollPanel 中放置多个树作为根。我只是更改了框的布局并使用相同的代码再创建一棵树,但是当我运行程序时,树并没有出现在我面前。

这是我的代码

import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;

public class SimpleTree extends JFrame {
  public static void main(String[] args) {
    new SimpleTree();
  }

  public SimpleTree() {
    super("Creating a Simple JTree");
    Container content = getContentPane();
    Object[] hierarchy =
      { "javax.swing",
        "javax.swing.border",
        "javax.swing.colorchooser",
        "javax.swing.event",
        "javax.swing.filechooser",
        new Object[] { "javax.swing.plaf",
                       "javax.swing.plaf.basic",
                       "javax.swing.plaf.metal",
                       "javax.swing.plaf.multi" },
        "javax.swing.table",
        new Object[] { "javax.swing.text",
                       new Object[] { "javax.swing.text.html",
                                      "javax.swing.text.html.parser" },
                       "javax.swing.text.rtf" },
        "javax.swing.tree",
        "javax.swing.undo" };
    DefaultMutableTreeNode root = processHierarchy(hierarchy);
    DefaultMutableTreeNode root2 = processHierarchy(hierarchy);
    JTree tree = new JTree(root);
    JTree tree2 = new JTree(root2);
    content.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
    content.add(new JScrollPane(tree));
    content.add(new JScrollPane(tree2));
    setSize(getPreferredSize());
    setVisible(true);
  }

  /** Small routine that will make node out of the first entry
   *  in the array, then make nodes out of subsequent entries
   *  and make them child nodes of the first one. The process is
   *  repeated recursively for entries that are arrays.
   */

  private DefaultMutableTreeNode processHierarchy(Object[] hierarchy) {
    DefaultMutableTreeNode node =
      new DefaultMutableTreeNode(hierarchy[0]);
    DefaultMutableTreeNode child;
    for(int i=1; i<hierarchy.length; i++) {
      Object nodeSpecifier = hierarchy[i];
      if (nodeSpecifier instanceof Object[])  // Ie node with children
        child = processHierarchy((Object[])nodeSpecifier);
      else
        child = new DefaultMutableTreeNode(nodeSpecifier); // Ie Leaf
      node.add(child);
    }
    return(node);
  }
}

有人可以帮我解决这个问题。所有帮助将不胜感激。

谢谢 Ashish Tyagi

4

2 回答 2

3

AJScrollPane可以查看其 中的单个子组件ViewPort

但是,您可以将 2 个JScrollPane组件放在一个面板上,例如均匀拆分GridLayout(2, 1)并将视图设置为JScrollPane新面板。

旁白:您应该将ContentPane用作容器BoxLayout

content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
于 2012-11-29T19:24:44.247 回答
2
于 2012-11-29T19:31:24.200 回答