[英]JTree does not display inside JScrollPane
我需要為我的程序顯示帳戶名稱,我想在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的視口(好)和JScrollPane本身(壞)。 不要那樣做。 只能通過JScrollPane的構造函數將其添加到JScrollPane的視口中,如上面第一行所示,或者在創建JScrollPane對象后調用setViewportView(...)
。
編輯:另一個問題是你使用setBounds(...)
。 您不應該這樣做,而應該使用布局管理器來正確查看您的組件。 您還需要在接受JScrollPane的任何容器上調用revalidate()
和repaint()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.