简体   繁体   English

JTree不会显示在JScrollPane中

[英]JTree does not display inside JScrollPane

I need to display account names for my program and I want to do this using JTree inside a JScrollPane. 我需要为我的程序显示帐户名称,我想在JScrollPane中使用JTree来完成此操作。

Here is my code: 这是我的代码:

public void loadAccounts() {

    accountsRoot = new DefaultMutableTreeNode("Accounts"); //create root

    accountsRoot.add(new DefaultMutableTreeNode("Fred")); //add one element
                                                          //for testing
    accounts = new JTree(accountsRoot);

    accountsPane = new JScrollPane(accounts);

    accountsPane.add(accounts);  //don't think this is necessary
    canvas.add(accountsPane);
    accounts.setBounds(0, 0, accountsPane.getWidth(), accountsPane.getHeight());
    accountsPane.setBounds(460, 270, 240, 410);
    accounts.setVisible(true);
    accountsPane.setVisible(true);

}

Because I am not using a layout I set the bounds manually. 因为我没有使用布局,所以我手动设置边界。

I can't seem to get it to show. 我似乎无法让它显示出来。 I want to eventually end up loading the accounts from a while so I figure JTree would be pretty easy for that, 我想最终最终加载帐户一段时间,所以我觉得JTree很容易,

accountsPane = new JScrollPane(accounts);

accountsPane.add(accounts);  //don't think this is necessary

Not only is that not necessary but it will mess things up as this in effect adds your accounts JTree to multiple containers -- to the JScrollPane's viewport (good) and to the JScrollPane itself (bad). 这不仅是必要的,而且会使事情变得混乱,因为这实际上将您的帐户JTree添加到多个容器 - JScrollPane的视口(好)和JScrollPane本身(坏)。 Don't do that. 不要那样做。 Add it to the JScrollPane's viewport only either through the JScrollPane's constructor as shown on the first line above, or by calling setViewportView(...) on the JScrollPane object after creating it. 只能通过JScrollPane的构造函数将其添加到JScrollPane的视口中,如上面第一行所示,或者在创建JScrollPane对象后调用setViewportView(...)

Edit: another problem is your use of setBounds(...) . 编辑:另一个问题是你使用setBounds(...) You shouldn't be doing this but rather should be using layout managers to allow the proper viewing of your components. 您不应该这样做,而应该使用布局管理器来正确查看您的组件。 You will also need to call revalidate() and repaint() on whatever container is accepting the JScrollPane. 您还需要在接受JScrollPane的任何容器上调用revalidate()repaint()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM