Reputation: 708
I need to display account names for my program and I want to do this using JTree inside a JScrollPane.
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,
Upvotes: 1
Views: 1856
Reputation: 285405
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). 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.
Edit: another problem is your use of 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.
Upvotes: 3