【问题标题】:JTree does not display inside JScrollPaneJTree 不显示在 JScrollPane 内
【发布时间】:2013-04-14 23:19:47
【问题描述】:

我需要为我的程序显示帐户名称,并且我想在 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 会很容易做到这一点,

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖 SSCCEaccountsPane.setBounds(460, 270, 240, 410); 这可能是问题的原因。 使用布局管理器。

标签: java swing jscrollpane jtree


【解决方案1】:
accountsPane = new JScrollPane(accounts);

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

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

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

【讨论】:

  • 即使没有第二行,我也看不到 JTree 正在显示。我应该看到至少两个元素,根和子,不是吗?
  • @F.Ali:见编辑回答。如需更多帮助,请考虑发布sscce
  • 是否可以为不使用布局管理器的包含组件中的一个组件使用布局管理器? revalidate() 和 repaint() 显示 JTree,但现在 JScrollPane 悬停在 JPanel 的中间中心。
  • @F.Ali:你需要学习和学习使用布局管理器、句点和故事结尾。这一切都会在教程中解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-16
  • 2023-03-30
相关资源
最近更新 更多