This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes selection JFileTree Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "selection JFileTree" Watch "selection JFileTree" New topic

selection JFileTree

Isaac Hewitt
Ranch Hand

Joined: Jul 24, 2006
Posts: 191


I am working with a JTree. I have a button in the toolbar, which when clicked, gets the path of a node selection in the JTree. If the button is pressed but nothing is selected in the JTree, this throws an exception.

<pre name="code" class="core"> String src = this.tree.getLastSelectedPathComponent().toString(); </pre>

I need to be able to detect whether there are no nodes selected. Thanks
Paul Clapham

Joined: Oct 14, 2005
Posts: 19751

What exception was that?
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 44569
JTrees are usually discussed on our Swing forum, so I shall move this discussion over there.
Craig Wood
Ranch Hand

Joined: Jan 14, 2004
Posts: 1535
You could break things up a bit and have a look at the selection state
<pre name="code" class="core">
Object o = this.tree.getLastSelectedPathComponent();
if(o != null) {
// okay to use o
String src = o.toString();
// or you could try something like
TreeSelectionModel tsm = tree.getSelectionModel();
// okay to query selection
Both JTree and TreeSelectionModel have methods such as getSelectionCount and getSelectionRows that you could use.
Isaac Hewitt
Ranch Hand

Joined: Jul 24, 2006
Posts: 191

ok thanks Craig. I will try those methods out.
I agree. Here's the link:
subject: selection JFileTree
It's not a secret anymore!