permaculture playing cards
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 Elasticsearch in Action this week in the Big Data 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: 19350

What exception was that?
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 41079
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.
Consider Paul's rocket mass heater.
subject: selection JFileTree