我正在尝试实现一个两边都有滚动窗格的分隔窗格。左边应该显示我正在尝试实现的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());
}我看到所有的节点都是有序的。
我做错了什么?我真的很感谢你的帮助和反馈!
发布于 2018-06-19 08:31:32
你的第二个
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();https://stackoverflow.com/questions/50923207
复制相似问题