我需要为我的程序显示帐户名称,我想使用 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 会很容易,
最佳答案
accountsPane = new JScrollPane(accounts);
accountsPane.add(accounts); //don't think this is necessary
这不仅没有必要,而且会把事情搞砸,因为这实际上会将您的帐户 JTree 添加到多个容器中——添加到 JScrollPane 的视口(viewport)(好的)和添加到 JScrollPane 本身(坏的)。不要那样做。只能通过上面第一行所示的 JScrollPane 构造函数或在创建 JScrollPane 对象后调用 setViewportView(...)
将其添加到 JScrollPane 的视口(viewport)。
编辑:另一个问题是您对 setBounds(...)
的使用。您不应该这样做,而应该使用布局管理器来正确查看您的组件。您还需要在接受 JScrollPane 的任何容器上调用 revalidate()
和 repaint()
。
关于java - JTree 不显示在 JScrollPane 内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16005483/