1

我需要为我的程序显示帐户名称,并且我想在 JScrollPane 中使用 JTree 来执行此操作。

这是我的代码:

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);

}

因为我没有使用布局,所以我手动设置了边界。

我似乎无法让它显示出来。我想最终从一段时间内加载帐户,所以我认为 JTree 会很容易,

4

1 回答 1

3
accountsPane = new JScrollPane(accounts);

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

这不仅没有必要,而且会搞砸,因为这实际上会将您的帐户 JTree 添加到多个容器中——添加到 JScrollPane 的视口(好)和 JScrollPane 本身(坏)。不要那样做。仅通过上面第一行所示的 JScrollPane 的构造函数或通过setViewportView(...)在创建 JScrollPane 对象后调用它来将其添加到 JScrollPane 的视口中。

编辑:另一个问题是您使用setBounds(...). 您不应该这样做,而应该使用布局管理器来允许正确查看您的组件。您还需要在任何接受 JScrollPane 的容器上调用revalidate()和。repaint()

于 2013-04-14T23:26:43.453 回答