Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

selection JFileTree

 
Isaac Hewitt
Ranch Hand
Posts: 191
Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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.

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

I need to be able to detect whether there are no nodes selected. Thanks
 
Paul Clapham
Sheriff
Posts: 21316
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What exception was that?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49771
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JTrees are usually discussed on our Swing forum, so I shall move this discussion over there.
 
Craig Wood
Ranch Hand
Pie
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could break things up a bit and have a look at the selection state
<blockquote>code:
<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();
if(!tsm.isSelectionPathEmpty())
// okay to query selection
</pre>
</blockquote>
Both JTree and TreeSelectionModel have methods such as getSelectionCount and getSelectionRows that you could use.
 
Isaac Hewitt
Ranch Hand
Posts: 191
Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok thanks Craig. I will try those methods out.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic